0

I want to sort an array like this

[
    {
        'type': 'apple', 
        'like': 3
    }, 
    {
        'type': 'pear', 
        'like': 5
    }, 
    ...
]

I was using lodash lib for the sorting. Is there a any more simple way to sort an array by like value?

Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
Kok Zhang
  • 3
  • 6

2 Answers2

2

How about pure JS sort method:

var k=[{'type': 'apple', 'like': 7}, {'type': 'pear', 'like': 5},{'type': 'pear', 'like': 10}];

console.log(k.sort((a,b)=>a.like-b.like));
If you want to understand it better, read it here.

I hope this helps. Thanks!

gorak
  • 5,233
  • 1
  • 7
  • 19
1

You can directly do this in javascript in the following manner:

var my_arr = [{'type': 'apple', 'like': 3}, {'type': 'pear', 'like': 5}, {'type': 'pea', 'like': 7}, {'type': 'orange', 'like': 1}, {'type': 'grape', 'like': 4}] 

console.log(my_arr)

my_arr.sort((a, b) => (a.like > b.like) ? 1 : -1)

console.log(my_arr)

where my_arr is the original array you were attempting to sort

Karan Shishoo
  • 2,402
  • 2
  • 17
  • 32