首页 > 解决方案 > 如何对数组进行排序取决于Javascript中的相同值

问题描述

例如,我有一个如下所示的数组。

const array = [
        {name: 'apple', type: 'fruit' },
        {name: 'computer', type: 'machine' },      
        {name: 'cherry', type: 'fruit' },
        {name: 'pear', type: 'fruit' },
        {name: 'galaxy', type: 'machine' },
        {name: 'KIA', type: 'car' },
               ]

排序后,

const sortedArray = {
    fruit: [
        {name: 'apple', type: 'fruit' },
        {name: 'cherry', type: 'fruit' },
        {name: 'pear', type: 'fruit' }
    ],
    car: [
        {name: 'KIA', type: 'car' }
    ],
    machine: [
        {name: 'computer', type: 'machine'},
        {name: 'galaxy', type: 'machine'}
    ]
}

所以我尝试如下

var sortedArray={}
for(let i=0; i< array.length; i++){
      this.sortedBags[this.bags[i].intent] = [];
}

我必须按下每个键。但我不知道该怎么做。
你能推荐一些更有效的代码吗?非常感谢您阅读它。

标签: javascript

解决方案


您首先需要对值进行排序,然后您需要对每个组进行排序

const array = [{name: 'apple', type: 'fruit' },{name: 'computer', type: 'machine' },{name: 'cherry', type: 'fruit' },{name: 'pear', type: 'fruit' },{name: 'galaxy', type: 'machine'},{name: 'KIA', type: 'car'}]

let sorted = array.reduce((op, inp) => {
  let type = inp.type;
  op[type] = op[type] || [];
  op[type].push(inp);
  return op
}, {})

for (let key in sorted) {
  let value = sorted[key];
  sorted[key] = value.sort((a, b) => a.name.localeCompare(b.name));
}

console.log(sorted)


推荐阅读