How can I sort an array with dictionarys? [Javascript]

Let’s say I have this array:

[
  {num: 0, otherdatas: 'blah'},
  {num: 5, otherdatas: 'blah'},
  {num: 3, otherdatas: 'blah'},
  {num: 8, otherdatas: 'blah'},
  {num: 9, otherdatas: 'blah'},
  {num: 4, otherdatas: 'blah'}
]

And I want to sort this array. like this:

[
  {num: 0, otherdatas: 'blah'},
  {num: 3, otherdatas: 'blah'},
  {num: 4, otherdatas: 'blah'},
  {num: 5, otherdatas: 'blah'},
  {num: 8, otherdatas: 'blah'},
  {num: 9, otherdatas: 'blah'}
]

If array was like [0, 5, 3, 8, 9, 4], sorting would be easy, but I have these numbers on dictionary. What can I do for this array?

Answer

You have an array and the array contains objects with two properties: num and otherdatas

  • -use the sort method on the array -sort will accept two parameters,that point to the current and the next item in the array -u need to compare these two parameters with either a-b or b-a condition so as to get the result in ascending or descending order -make sure while comparing use a.num and b.num as the a and b here are not primitives but objects -a new array will be returned,store the array in some variable

const arr1 = [
  {num: 0, otherdatas: 'blah'},
  {num: 5, otherdatas: 'blah'},
  {num: 3, otherdatas: 'blah'},
  {num: 8, otherdatas: 'blah'},
  {num: 9, otherdatas: 'blah'},
  {num: 4, otherdatas: 'blah'}
]

const sortedArr = arr1.sort(function(a,b){
return a.num - b.num;
//OR
// return b.num-a.num ;
})