Sorting


After ES 2017

[...myArray].sort(mySortFunction); 


Sorting Numbers in an Array

Numbers are not sorted alphabetical order
The function must return a zero if the numbers are equal.
The function must return a negative number if the items are in the correct sequence
The function must return a positive number if the items need to be swapped.

write([6, 4, 2, 27, 17].sort( function (first, second) { 
   return first - second;
}


Sorting an Array of Key-Value pairs

myArrayOfObjects = [ 
   { name: "one", age:5 },
   { name: "two", age:8 }
];

function sortByAge(a, b) {
   if (a.age === b.age) {
      return 0;
   }
   return a.age - b.age;
};

const sortByName(a, b) => {
   if (a.name === b.name) {
      return 0;
   }
   return a.name > b.name ? 1 : -1;
};

const newArray = myArrayOfObjects.sort(sortByName); // this changes the original array
const newArray = [ ...myArrayOfObjects].sort(sortByName); // this makes a copy first


© 2023 Better Solutions Limited. All Rights Reserved. © 2023 Better Solutions Limited TopPrevNext