0

For example, I have an array like below.

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' },
               ]

after sorting,

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'}
    ]
}

So I tried like below

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

And I have to push into each key. But I don't know how to do this.
Could you recommend some more efficient code? Thank you so much for reading it.

DD DD
  • 1,148
  • 1
  • 10
  • 33

1 Answers1

1

You first need to sort the value and then you need to sort each group

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)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60