0

I have an object that looks like this

[{group: 'Group-B', items[{ count : 3, item : 'item-A' }]},
 {group: 'Group-B', items[{ count : 8, item : 'item-C' }]},
 {group: 'Group-A', items[{ count : 4, item : 'item-H' }]},
 {group: 'Group-C', items[{ count : 2, item : 'item-F' }]}
]

The RESULT should read: desc by count

[{group: 'Group-B', items[{ count : 8, item : 'item-C' }]},
 {group: 'Group-A', items[{ count : 4, item : 'item-H' }]},
 {group: 'Group-B', items[{ count : 3, item : 'item-A' }]},
 {group: 'Group-C', items[{ count : 2, item : 'item-F' }]}
]

I need to sort this whole object by count.
Ive been looking at lodash, but I cant figure out how to do this.

enter image description here

morne
  • 4,035
  • 9
  • 50
  • 96

3 Answers3

0

You can do it so

const array = [
 {group: 'Group-B', items:[{ count : 3, item : 'item-A' }]},
 {group: 'Group-B', items:[{ count : 8, item : 'item-C' }]},
 {group: 'Group-A', items:[{ count : 4, item : 'item-H' }]},
 {group: 'Group-C', items:[{ count : 2, item : 'item-F' }]}
]

const result = array.sort((a, b) => {
  return a.items[0].count - b.items[0].count
})

console.log(JSON.stringify(result))
AlexAV-dev
  • 1,165
  • 4
  • 14
0

hope it helps. you can remove .slice() function if you don't want to create a copy of original array.

let obj = [
    {group: 'Group-B', items: [{count: 3, item: 'item-A'}]},
    {group: 'Group-B', items: [{count: 8, item: 'item-C'}]},
    {group: 'Group-A', items: [{count: 4, item: 'item-H'}]},
    {group: 'Group-C', items: [{count: 2, item: 'item-F'}]}
]
console.log(obj)

let sorted = obj.slice().sort((a,b) => {
    if(a.items[0].count < b.items[0].count){
        return -1
    }
    if(a.items[0].count > b.items[0].count){
        return 1
    }
    else
        return 0
});
console.log(sorted)
Caner Sevince
  • 39
  • 1
  • 3
0

If you want to sort by the number of elements in items, you could do this:

myArray.sort(function(itemA, itemB) {return itemA.items.count - itemB.items.count; });

if you want to sort by the attribute "count" that is in each element in the array items, you will have to detail how you compare these elements. But what you are looking for must be the Array.sort() function: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/sort

Bamak
  • 188
  • 6