how does array.sort work in javascript code example

Example 1: sort javascript array

var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)

Example 2: javascript string array sort alphabetically

var items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair'];
items.sort((a, b) =>
   a.localeCompare(b)//using String.prototype.localCompare()
);

Example 3: javascript sort array strings alphabetically

//sort array alphabetically
objArray.sort(function(a, b) {
   return a.localeCompare(b);
});

Example 4: sorting of arraray's number element in javascript

let numbers = [0, 1, 2, 3, 10, 20, 30];
numbers.sort((a, b) => a - b);

console.log(numbers);

Example 5: sort arrays according to first array js

itemsArray.sort(function(a, b){  
  return sortingArr.indexOf(a) - sortingArr.indexOf(b);
});

Example 6: how to sort array

array sorting

Tags:

Cpp Example