JavaScript sort array of numbers Code Example

Last Updated On Thursday 20th Jan 2022
  • sort The function can sort the array elements in ascending order.
  • If the elements are strings, they are sorted in ascending order.
  • The sort function changes the value of the array itself.

Working with numbers.Each number is converted into a string, and each number is compared with its position in Unicode.

  • With ES6, simply using with arrow functions
	let numArr = [1, 5, 6, 7, 2, 4, 3, 8, 9];
	

Example 1 : Sorting numbers ascending

	console.log(numArr.sort((a, b) => a - b));
// [ 1,2,3,4,5,6,7,8,9 ]
	

Example 2 : Sorting numbers descending

	console.log(numArr.sort((a, b) => b - a));
// [ 9,8,7,6,5,4,3,2,1 ]