根据两个属性值对对象数组进行排序

时间:2020-06-03 22:44:52

标签: javascript typescript ecmascript-6 ecmascript-5

我有一个对象数组:

let items = [
  { name: 'eric', type: 'comparable',  value: 1 },
  { name: 'bob', type: 'comparable', value: 4 },
  { name: 'michael', type: 'comparable', value: 0 },
  { name: 'john', type: 'comparable', value: 3 },
  { name: 'brad', type: 'incomparable', value: null },
  { name: 'james', type: 'incomparable', value: 5},
  { name: 'martin', type: 'comparable', value: 2 },
  { name: 'chris', type: 'comparable', value: null }
];

我想对数组进行排序,以便可以通过以下方式对对象进行排序:

  • 首先,根据“类型”属性->如果它是=“可比较”->根据“值”属性对其进行排序

  • 第二,根据“值”属性->如果为null,则将其放在数组底部

通过“值”属性,如果为null,则将对象放在数组底部,如下所示:

  { name: 'michael', type: 'comparable', value: 0 },
  { name: 'eric', type: 'comparable',  value: 1 },
  { name: 'martin', type: 'comparable', value: 2 },
  { name: 'john', type: 'comparable', value: 3 },
  { name: 'bob', type: 'comparable', value: 4 },
  { name: 'chris', type: 'comparable', value: null },
  { name: 'brad', type: 'incomparable', value: null },
  { name: 'james', type: 'incomparable', value: 5}

我已经做到了:

items.sort((a, b) => {
    return (a.value===null)-(b.value===null) || +(a.value>b.value)||-(a.ordre<b);
});

但是像这样,我总是根据“ value”属性进行排序,我希望它首先查找该属性

(我不会使用loadash)

建议?

2 个答案:

答案 0 :(得分:1)

如果逻辑读法与您描述逻辑的方式相似,我个人会更容易阅读。在此示例中,我尝试将需求描述为一系列if语句,而不是单个逻辑表达式:

let items = [
  { name: 'eric', type: 'comparable',  value: 1 },
  { name: 'bob', type: 'comparable', value: 4 },
  { name: 'michael', type: 'comparable', value: 0 },
  { name: 'john', type: 'comparable', value: 3 },
  { name: 'brad', type: 'incomparable', value: null },
  { name: 'james', type: 'incomparable', value: 5},
  { name: 'martin', type: 'comparable', value: 2 },
  { name: 'chris', type: 'comparable', value: null }
];

console.log(items.sort((a, b) => {
  if (a.type === 'comparable' && b.type === 'comparable') {
    if (a.value == null) return 1;
    return a.value - b.value;
  }
  if (a.type === 'comparable') return -1;
  return 1;
}));

答案 1 :(得分:0)

您可以执行localeCompare中的type,然后在类型相同的情况下进行布尔短路。在表达式的第二部分,您可以求值value,将null强制为Infinity以将其移至末尾。

const items = [
  { name: 'eric', type: 'comparable',  value: 1 },
  { name: 'bob', type: 'comparable', value: 4 },
  { name: 'michael', type: 'comparable', value: 0 },
  { name: 'john', type: 'comparable', value: 3 },
  { name: 'brad', type: 'incomparable', value: null },
  { name: 'james', type: 'incomparable', value: 5},
  { name: 'martin', type: 'comparable', value: 2 },
  { name: 'chris', type: 'comparable', value: null }
];

items.sort((a, b) => a.type.localeCompare(b.type)
  || (a.value != null ? a.value : Infinity) - (b.value != null ? b.value : Infinity));

console.log(items);