Sorting an Array

PHOTO EMBED

Wed Nov 01 2023 18:46:34 GMT+0000 (Coordinated Universal Time)

Saved by @abhikash01

const numbers = [102, -1, 2];
 
numbers.sort((a, b) => a - b);
 
console.log(numbers);
content_copyCOPY

Here, the sort() method is called on the numbers array, which takes the comparator function as an argument. The comparator function takes 2 arguments ‘a’ and ‘b’, which are the elements being compared. The comparator function returns a positive value if ‘a’ must come before/equal to ‘b’ and a negative value if ‘a’ must come after ‘b’.