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
  • 7,224
  • 8
  • 49
  • 71
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!

Rajan
  • 4,939
  • 1
  • 5
  • 17
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,217
  • 2
  • 16
  • 30