Reading history

Sorting, Searching and Grouping Arrays in JavaScript

6 min read 2 views

Sort numbers, strings and objects correctly, use toSorted and with, search with find, some and every, and group, flatten and create arrays.

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 localeCompare and objects by several keys
  • Non-mutating toSorted, toReversed and with
  • Searching with find, findLast, some, every and includes
  • Grouping with Object.groupBy, flattening and Array.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 if a should come first, a positive number if b should, and 0 if they are equal. a - b sorts numbers up; b - a sorts 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, localeCompare returns 0 and the CGPA comparison decides. Sorting is stable, so items that compare equal keep their original order.
  • sort() and reverse() change the original array. toSorted(), toReversed() and with(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
  • find returns the first matching item (or undefined), findIndex its position (or -1). findLast and findLastIndex search from the end.
  • some asks “does at least one match?” and every asks “do all match?”. Both stop as soon as the answer is known.
  • includes finds NaN, but indexOf does not, because it uses ===.
  • Object.groupBy(array, fn) sorts items into groups using the key returned by fn. 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. flatMap maps 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, and fill sets every item.
  • at(-1) reads the last item without writing arr[arr.length - 1].

Which Method Should You Use?

QuestionMethodReturns
Which item matches?find, findLastItem or undefined
Where is it?findIndex, indexOfIndex or -1
Is a value in the array?includesBoolean
Does any / every item match?some / everyBoolean
All matching items?filterNew array
Items in groups?Object.groupByObject of arrays
Sorted copy?toSortedNew array

Common Mistakes

  1. Sorting numbers without a compare function.
  2. Returning a boolean from the compare function, such as (a, b) => a > b. It must return a negative, zero or positive number.
  3. Forgetting that sort() changes the original, then wondering why another part of the page reordered.
  4. Using filter(...)[0] to find one item; find is 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 localeCompare for text and || to sort by several keys.
  • Prefer toSorted and friends to avoid changing shared arrays.
  • find, some, every, groupBy, flat and Array.from cover most other needs.

Next: Object Methods: keys, entries, freeze and More.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *