I have an array of objects that I need to sort based on a value inside each object:
array: [
{
number: 1000
},
{
number: 700
},
{
number: 4000
},
]
How can I sort the array based on that specific key/value pair?
Thanks!
I have an array of objects that I need to sort based on a value inside each object:
array: [
{
number: 1000
},
{
number: 700
},
{
number: 4000
},
]
How can I sort the array based on that specific key/value pair?
Thanks!
Run a sort function on it. Arrays have a method called sort
that allows you to pass a function to it so that you can define how you want it to sort. Or in this case, since you are trying to sort an array of objects, which key of that object to sort by:
var unsorted = [{
number: 1000
}, {
number: 700
}, {
number: 4000
}, ]
var sorted = unsorted.sort(function(a, b) {
return a.number - b.number;
})
console.log(sorted);