How do you sort an array in JavaScript without using a library?
At first glance, it seems simple enough:
const result = ['cat', 'axe', 'ball'].sort();
console.log(result); // ['axe', 'ball', 'cat']
const result = ['cat', 'axe', 'ball'].sort();
console.log(result); // ['axe', 'ball', 'cat']
But things getting slightly unexpected when we do that with number:
const result = [5, 10, 2, 100].sort();
console.log(result); // [10, 100, 2, 5]
const result = [5, 10, 2, 100].sort();
console.log(result); // [10, 100, 2, 5]
Many would solve this by providing a comparator function:
const result = [5, 10, 2, 100].sort((a, b) => a - b);
console.log(result); // [2, 5, 10, 100]
const result = [5, 10, 2, 100].sort((a, b) => a - b);
console.log(result); // [2, 5, 10, 100]
What about this?
const result = ['Item 5', 'Item 10', 'Item 2'].sort();
console.log(result); // ['Item 10', 'Item 2', 'Item 5']
const result = ['Item 5', 'Item 10', 'Item 2'].sort();
console.log(result); // ['Item 10', 'Item 2', 'Item 5']
Answer: Intl.Collator
. A class designed for string comparison.
const collator = new Intl.Collator('en', { numeric: true });
const result = ['Item 5', 'Item 10', 'Item 2'].sort(collator.compare);
console.log(result); // ['Item 2', 'Item 5', 'Item 10']
const collator = new Intl.Collator('en', { numeric: true });
const result = ['Item 5', 'Item 10', 'Item 2'].sort(collator.compare);
console.log(result); // ['Item 2', 'Item 5', 'Item 10']