-1

I want to order a javascript list containing object according to a key,

var a = [{order: 1, item: 'shoes'}, {order: 3, item: 'jeans'}, {order: 2, item: 'shirt'}, {order: 1, item: 'coat'}]

Here I want to order according to order from lower to upper like:

var b = a.filter(data => data.order) // have some check here

How can I do that ?

varad
  • 7,309
  • 20
  • 60
  • 112

2 Answers2

0

you need to sort by the property so you can use a functional style to curry the key, and return a function that Array.prototype.sort can use.

var clothes = [
  { order: 1, item: 'shoes' }, 
  { order: 3, item: 'jeans' }, 
  { order: 2, item: 'shirt' }, 
  { order: 1, item: 'coat' }
]

const sortBy = key => (a, b) => a[key] - b[key]

console.log(
  clothes.sort(sortBy('order'))
)
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
synthet1c
  • 6,152
  • 2
  • 24
  • 39
-2

If you are using lodash, you can do (docs)

_.sortBy(list, el => el.order);

If you are not (and I believe you should), you can take a look at their source code for hints ;)

Luan Nico
  • 5,376
  • 2
  • 30
  • 60