【问题标题】:sort array by property without using the first object按属性排序数组而不使用第一个对象
【发布时间】:2020-04-22 13:32:58
【问题描述】:

我有一个对象数组,我想按对象 ID 对它们进行排序。 我尝试使用 options.sort((a, b) => a.id.localeCompare(b.id)); 但没有按预期工作,因为它甚至对“所有”对象进行排序,我不想要这个(id=“所有”的对象应该在我的数组中排在第一位,之后应该是升序的对象)。下面你可以看到我的代码的输入和输出

输入:

 var items = 
           [{ 'Name':'All', 'id': 'all'
            { 'Name':'item1', 'id': '003' }
            { 'Name':'item2', 'id': '001' }
            { 'Name':'item3', 'id': '002' }];

输出:

  var items = 
           [{ 'Name':'item2', 'id': '001' }
            { 'Name':'item3', 'id': '002' }
            { 'Name':'item1', 'id': '003' }
            { 'Name':'All', 'id': 'all'}];

【问题讨论】:

  • 用干净的语法再次在评论中修改了答案。

标签: arrays angular


【解决方案1】:

 function compare(key, order = 'desc') {
  return (a, b) => {
    if (a[key] > b[key])
      return order === 'desc' ? -1 : 1;
    if (a[key] < b[key])
      return order === 'desc' ? 1 : -1;
    return 0;
  };
 }


const data = [
      { 'Name':'All', 'id': 'all'},
      { 'Name':'item3', 'id': '003' },
      { 'Name':'item1', 'id': '001' },
      { 'Name':'item2', 'id': '002' }
 ];
 
 const sortedData = data.sort(compare('Name', 'asce'));
 console.log('sorted: ', sortedData);

【讨论】:

    【解决方案2】:

    它应该可以工作

    var items = 
               [{ 'Name':'All', 'id': 'all' },
                { 'Name':'item1', 'id': '003' },
                { 'Name':'item2', 'id': '001' },
                { 'Name':'item3', 'id': '002' }];
                
       items.sort((a, b) => ((typeof b.id === "number") - (typeof a.id === "number")) || (a.id > b.id ? 1 : -1));
    
    // items.sort((a, b) => (((typeof b.id === "number") as any) - ((typeof a.id === "number") as any)) || (a.id > b.id ? 1 : -1) );
    
      console.log(items)

    【讨论】:

    • 我得到这个错误'算术运算的左侧必须是'any'、'number'、'bigint'或枚举类型。对于 typeof 部分..
    • 更新了答案。尝试使用注释的类型支持
    • @user2004 答案在注释中再次修改,语法简洁。
    猜你喜欢
    • 1970-01-01
    • 2023-01-06
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多