-1

What am trying to do is to order the above items with the length of variant such that after the order the second item will be first since it has 3 items in the variant array

I have the following data structure and code:

var items = [
 {name: 'one', variant: [{id: 1, name: 'ABS'}, ]},  
 {name: 'second', variant: [{id: 1, name: 'BTC'}, {id: 2, name: 'SAM'}, {id: 2, name: 'KXD'}]}
]

console.log(items.sort((a, b) => a.variant.length > b.variant.length))

But this does not sort the items. What am i missing as i would like to do this in ES6

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
Geoff
  • 6,277
  • 23
  • 87
  • 197
  • Note per e.g. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort that the callback to sort probably shouldn't just return a boolean – jonrsharpe Feb 27 '20 at 12:42
  • 2
    `.sort((a, b) => b.variant.length - a.variant.length)` will do it – Calvin Nunes Feb 27 '20 at 12:45

1 Answers1

2

You have to return 1, -1 , or 0
If you want to change to order, swap 1 with -1.

items.sort((a,b)=>{
        if(a.variant.length > b.variant.length)
            return 1;
        else if (b.variant.length > a.variant.length)
            return -1;
        else // if a.variant.length === b.variant.length
            return 0;
     })
KDani-99
  • 145
  • 8