Sort an array of integers JavaScript

Last Updated On Tuesday 5th Oct 2021

JavaScript Array Sort

The sort() method sorts the elements of an array in place and returns the sorted array.

Syntax

	sort()
sort((firstEl, secondEl) => { ... } )
	

Parameters

  • firstEl – The first element for comparison.
  • secondEl – The second element for comparison.

By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts

JavaScript Sort Array of Numbers

	let numArray = [111, 333, 222];
numArray.sort(function(a, b) {
  return a - b;
});

console.log(numArray);
	
	// [ 111, 222, 333 ]
	

You can also be done in one line .

	let numArray = [111, 333, 222];
numArray = numArray.sort(( a, b ) => b - a );

console.log(numArray)
	
	// [ 333, 222, 111 ]
	

References