JavaScript sorting and the default sort pitfall

Array.prototype.sort with no argument converts the elements to strings and compares them as text. The numbers 10, 9, and 1 become "10", "9", and "1", which sort as 1, 10, 9. To sort numbers, pass a comparison function that returns a negative number, zero, or a positive number: (a, b) => a - b for ascending order. sort also changes the array in place.

JavaScript
console.log([10, 9, 1].sort().join(","));
console.log([10, 9, 1].sort((a, b) => a - b).join(","));

function mergeSort(items) {
  if (items.length <= 1) {
    return items;
  }
  const middle = Math.floor(items.length / 2);
  const left = mergeSort(items.slice(0, middle));
  const right = mergeSort(items.slice(middle));
  const merged = [];
  let i = 0;
  let j = 0;
  while (i < left.length && j < right.length) {
    merged.push(left[i] <= right[j] ? left[i++] : right[j++]);
  }
  return merged.concat(left.slice(i), right.slice(j));
}
console.log(mergeSort([5, 2, 9, 1, 5, 6]).join(","));

const people = [
  { name: "Ada", age: 30 },
  { name: "Bo", age: 25 },
  { name: "Cy", age: 30 },
  { name: "Di", age: 25 },
];
people.sort((p, q) => p.age - q.age);
console.log(people.map((p) => p.name).join(","));

console.log(["pear", "Apple", "fig"].sort((a, b) => a.localeCompare(b)).join(","));
Read the full lesson