Sorting a list of numbers in JavaScript gives a surprise on day one: [100, 25, 3].sort() puts 100 first. Once you know why, sorting becomes easy and powerful, from ranking students by department and grade to ordering names in any language. This lesson covers sorting with compare functions, the newer methods that return sorted copies, and the array methods for searching, grouping, flattening and creating arrays that go beyond map, filter and reduce.
In this lesson you will learn
- Why
sort()needs a compare function for numbers - Sorting strings with
localeCompareand objects by several keys - Non-mutating
toSorted,toReversedandwith - Searching with
find,findLast,some,everyandincludes - Grouping with
Object.groupBy, flattening andArray.from
You should know arrays and higher-order functions.
Sorting Correctly
"use strict";
// sort() compares items as STRINGS by default
const nums = [100, 25, 3, 1000, 42];
console.log([...nums].sort()); // surprising order
console.log([...nums].sort((a, b) => a - b)); // ascending numbers
console.log([...nums].sort((a, b) => b - a)); // descending
// Strings: localeCompare handles case and accents properly
const names = ["rina", "Arif", "Émile", "tania", "Babu"];
console.log([...names].sort());
console.log([...names].sort((a, b) => a.localeCompare(b)));
// Objects: sort by one key, then another (sort is stable)
const students = [
{ name: "Rina", dept: "CSE", cgpa: 3.8 },
{ name: "Arif", dept: "EEE", cgpa: 3.5 },
{ name: "Tania", dept: "CSE", cgpa: 3.9 },
{ name: "Nabil", dept: "EEE", cgpa: 3.8 },
];
const ranked = students.toSorted((a, b) =>
a.dept.localeCompare(b.dept) || b.cgpa - a.cgpa);
console.log(ranked.map(s => `${s.dept} ${s.name} ${s.cgpa}`).join(" | "));
console.log("original first:", students[0].name); // toSorted did not change it
// sort() changes the array in place; toSorted, toReversed and with return copies
const week = ["Sat", "Sun", "Mon"];
const rev = week.toReversed();
const fixed = week.with(1, "SUN");
console.log(week, rev, fixed);
Output
[ 100, 1000, 25, 3, 42 ]
[ 3, 25, 42, 100, 1000 ]
[ 1000, 100, 42, 25, 3 ]
[ 'Arif', 'Babu', 'rina', 'tania', 'Émile' ]
[ 'Arif', 'Babu', 'Émile', 'rina', 'tania' ]
CSE Tania 3.9 | CSE Rina 3.8 | EEE Nabil 3.8 | EEE Arif 3.5
original first: Rina
[ 'Sat', 'Sun', 'Mon' ] [ 'Mon', 'Sun', 'Sat' ] [ 'Sat', 'SUN', 'Mon' ]
- Without arguments,
sort()converts items to strings and compares them character by character, so “1000” comes before “25” just as “ba” comes before “c”. - A compare function
(a, b) => ...returns a negative number ifashould come first, a positive number ifbshould, and 0 if they are equal.a - bsorts numbers up;b - asorts them down. - The default string sort puts capital letters before lower-case ones and accented letters last.
a.localeCompare(b)sorts the way people expect, using the rules of a language. - For several keys, compare the first key and fall back to the second with
||: when the departments match,localeComparereturns 0 and the CGPA comparison decides. Sorting is stable, so items that compare equal keep their original order. sort()andreverse()change the original array.toSorted(),toReversed()andwith(index, value)return a new array and leave the original untouched, which is safer when other code uses the same array.
Searching, Grouping and Creating Arrays
"use strict";
const orders = [
{ id: 1, item: "Pen", qty: 10, price: 15, paid: true },
{ id: 2, item: "Notebook", qty: 3, price: 80, paid: false },
{ id: 3, item: "Bag", qty: 1, price: 1200, paid: true },
{ id: 4, item: "Pen", qty: 5, price: 15, paid: false },
];
// Searching
console.log(orders.find(o => o.price > 50).item, orders.findIndex(o => o.item === "Bag"));
console.log(orders.findLast(o => o.item === "Pen").id, orders.some(o => !o.paid), orders.every(o => o.qty > 0));
console.log([1, 2, NaN].includes(NaN), [1, 2, NaN].indexOf(NaN));
// Grouping
const byStatus = Object.groupBy(orders, o => (o.paid ? "paid" : "unpaid"));
console.log(Object.keys(byStatus), byStatus.unpaid.map(o => o.id));
// Flattening
const timetable = [["Math", "Physics"], ["Bangla"], ["ICT", ["Lab"]]];
console.log(timetable.flat(), timetable.flat(Infinity));
const words = ["learn web", "build apps"].flatMap(s => s.split(" "));
console.log(words);
// Creating arrays
console.log(Array.from({ length: 5 }, (_, i) => (i + 1) ** 2));
console.log(Array.from("hello"), Array.of(7), new Array(3).fill(0));
console.log(orders.at(-1).item, orders.map(o => o.qty * o.price).reduce((s, x) => s + x, 0));
Output
Notebook 2
4 true true
true -1
[ 'paid', 'unpaid' ] [ 2, 4 ]
[ 'Math', 'Physics', 'Bangla', 'ICT', [ 'Lab' ] ] [ 'Math', 'Physics', 'Bangla', 'ICT', 'Lab' ]
[ 'learn', 'web', 'build', 'apps' ]
[ 1, 4, 9, 16, 25 ]
[ 'h', 'e', 'l', 'l', 'o' ] [ 7 ] [ 0, 0, 0 ]
Pen 1665
findreturns the first matching item (orundefined),findIndexits position (or -1).findLastandfindLastIndexsearch from the end.someasks “does at least one match?” andeveryasks “do all match?”. Both stop as soon as the answer is known.includesfindsNaN, butindexOfdoes not, because it uses===.Object.groupBy(array, fn)sorts items into groups using the key returned byfn. It is a recent addition, supported in current browsers and Node.js 21 and later.flat()removes one level of nesting;flat(Infinity)removes all.flatMapmaps each item to an array and flattens the result in one step.Array.from({ length: 5 }, fn)builds an array by calling a function for each position.Array.from("hello")splits a string into characters, andfillsets every item.at(-1)reads the last item without writingarr[arr.length - 1].
Which Method Should You Use?
| Question | Method | Returns |
|---|---|---|
| Which item matches? | find, findLast | Item or undefined |
| Where is it? | findIndex, indexOf | Index or -1 |
| Is a value in the array? | includes | Boolean |
| Does any / every item match? | some / every | Boolean |
| All matching items? | filter | New array |
| Items in groups? | Object.groupBy | Object of arrays |
| Sorted copy? | toSorted | New array |
Common Mistakes
- Sorting numbers without a compare function.
- Returning a boolean from the compare function, such as
(a, b) => a > b. It must return a negative, zero or positive number. - Forgetting that
sort()changes the original, then wondering why another part of the page reordered. - Using
filter(...)[0]to find one item;findis clearer and stops early.
Practice Exercises
Exercise 1. Sort products by price from lowest to highest, without changing the original array.
Show answer
const cheapestFirst = products.toSorted((a, b) => a.price - b.price);
Exercise 2. Check whether every mark in [67, 82, 45, 90] is a pass (40 or more) and find the first mark above 80.
Show answer
const marks = [67, 82, 45, 90];
console.log(marks.every(m => m >= 40), marks.find(m => m > 80)); // true 82
Frequently Asked Questions
How do I sort an array randomly?
Do not use sort(() => Math.random() - 0.5); it gives a biased shuffle. Use the Fisher-Yates algorithm: loop from the end and swap each item with a randomly chosen item at or before it.
Can I use toSorted in older browsers?
toSorted, toReversed and with work in all current browsers. For very old browsers, use [...arr].sort(fn), which also sorts a copy.
Summary
- Always pass a compare function when sorting numbers or objects.
- Use
localeComparefor text and||to sort by several keys. - Prefer
toSortedand friends to avoid changing shared arrays. find,some,every,groupBy,flatandArray.fromcover most other needs.
