This page looks best with JavaScript enabled

Array Sort in Javascript

 ·   ·  ☕ 2 min read

Arrays in Javascript can be sorted using a simple .sort command. But, don’t let that simplicity deceive you - it goes far more than that.

1
2
let arr = [4, 2, 1, 7, 3];
console.log(arr.sort()); // [ 1, 2, 3, 4, 7 ]

Sort can be used against full strings -

1
2
3
let fruits = ["orange", "apple", "grapes"];
console.log("fruits.sort(): ", fruits.sort());
//[ 'apple', 'grapes', 'orange' ]

It can use a custom function instead of the default sort logic.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const fruits = [
  { name: "orange", color: "orange" },
  { name: "apple", color: "red" },
  { name: "grapes", color: "green" },
];
const fruitsSorted = fruits.sort((fruit1, fruit2) => {
  if (fruit1.color < fruit2.color) return -1;
  else if (fruit1.color > fruit2.color) return 1;
  else return 0;
});
console.log("fruitsSorted: ", fruitsSorted);

/* output
fruitsSorted:  [
  { name: 'grapes', color: 'green' },
  { name: 'orange', color: 'orange' },
  { name: 'apple', color: 'red' }
]
*/

You can use any custom logic in the sort function, which makes it quite a powerful tool. However do remember - sort affects the original array.

For e.g. the above code sorts the array fruits even though you are sorting fruitsSorted.

1
console.log("fruits: ", fruits);

Avoid this by using copying array before sort. The quickest way to do that is outlined below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// ...

const fruitsSorted = [...fruits];

fruitsSorted.sort((fruit1, fruit2) => {
  if (fruit1.color < fruit2.color) return -1;
  else if (fruit1.color > fruit2.color) return 1;
  else return 0;
});
console.log("fruitsSorted: ", fruitsSorted);

// same output as above
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things