LearnFrenzy
Sign in Take a free test

Arrays · Lesson 17 of 40

Sorting, Searching and Grouping Arrays

4 min read Updated Nov 7, 2026 Saurabh Samir

Sorting looks easy until [10, 9, 1].sort() returns [1, 10, 9]. This lesson explains why, shows how to sort numbers, text and objects correctly, and covers the other everyday data jobs: removing duplicates, grouping, and searching large sorted lists quickly.

In this lesson

  • The default sort pitfall and comparator functions
  • Sorting objects by one or more keys
  • Unique values, grouping and counting
  • Binary search on sorted data

The default sort compares strings

console.log([10, 9, 1, 100].sort());          // converted to strings: "1" < "10" < "100" < "9"
console.log([10, 9, 1, 100].sort((a, b) => a - b));    // ascending numbers
console.log([10, 9, 1, 100].sort((a, b) => b - a));    // descending

Output

[ 1, 10, 100, 9 ]
[ 1, 9, 10, 100 ]
[ 100, 10, 9, 1 ]

How a comparator (a, b) works

Return value of compare(a, b)

  • negativea comes first
  • positiveb comes first
  • zerokeep their current order (sort is stable)

Common mistake: sort mutates

sort() sorts the array in place and returns it, so const sorted = arr.sort() also changes arr. Use arr.toSorted(compare) for a sorted copy.

Sorting strings

const cities = ["pune", "Agra", "Ēluru", "delhi", "Bengaluru"];
console.log(cities.toSorted());
console.log(cities.toSorted((a, b) => a.localeCompare(b)));
console.log(["file10", "file2", "file1"].toSorted((a, b) => a.localeCompare(b, undefined, { numeric: true })));

Output

[ 'Agra', 'Bengaluru', 'delhi', 'pune', 'Ēluru' ]
[ 'Agra', 'Bengaluru', 'delhi', 'Ēluru', 'pune' ]
[ 'file1', 'file2', 'file10' ]

Sorting objects by one or more keys

const team = [
  { name: "Ravi", dept: "QA", salary: 60000 },
  { name: "Asha", dept: "Dev", salary: 95000 },
  { name: "Meera", dept: "Dev", salary: 95000 },
  { name: "Kiran", dept: "QA", salary: 72000 },
];
// dept A→Z, then salary high→low, then name A→Z
const sorted = team.toSorted(
  (a, b) =>
    a.dept.localeCompare(b.dept) ||
    b.salary - a.salary ||
    a.name.localeCompare(b.name)
);
for (const p of sorted) console.log(p.dept, p.salary, p.name);

Output

Dev 95000 Asha
Dev 95000 Meera
QA 72000 Kiran
QA 60000 Ravi

The || chain works because a comparator returns 0 for a tie, and 0 is falsy – so JavaScript moves to the next key only when the previous one is equal.

Unique values

const tags = ["js", "sql", "js", "css", "sql"];
console.log([...new Set(tags)]);

const users = [{ id: 1, n: "A" }, { id: 2, n: "B" }, { id: 1, n: "A again" }];
const uniqueById = [...new Map(users.map((u) => [u.id, u])).values()];
console.log(uniqueById);       // last one wins for each id

Output

[ 'js', 'sql', 'css' ]
[ { id: 1, n: 'A again' }, { id: 2, n: 'B' } ]

Grouping with Object.groupBy

const tickets = [
  { id: 1, priority: "high" }, { id: 2, priority: "low" },
  { id: 3, priority: "high" }, { id: 4, priority: "medium" },
];
const byPriority = Object.groupBy(tickets, (t) => t.priority);
console.log(Object.keys(byPriority));
console.log(byPriority.high.map((t) => t.id));

const marks = [91, 38, 77, 55, 82];
const result = Object.groupBy(marks, (m) => (m >= 40 ? "pass" : "fail"));
console.log(result.pass, result.fail);

Output

[ 'high', 'low', 'medium' ]
[ 1, 3 ]
[ 91, 77, 55, 82 ] [ 38 ]

Object.groupBy (ES2024) replaces the classic reduce-into-object pattern. Map.groupBy does the same but returns a Map, which allows non-string keys.

Binary search on sorted data

indexOf and find check items one by one – O(n). On a sorted array, binary search halves the range each step – O(log n): about 20 steps for a million items.

function binarySearch(sorted, target) {
  let lo = 0, hi = sorted.length - 1, steps = 0;
  while (lo <= hi) {
    steps++;
    const mid = Math.floor((lo + hi) / 2);
    if (sorted[mid] === target) return { index: mid, steps };
    if (sorted[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return { index: -1, steps };
}
const ids = Array.from({ length: 1_000_000 }, (_, i) => i * 2);   // 0, 2, 4, …
console.log(binarySearch(ids, 1_234_568));
console.log(binarySearch(ids, 7));

Output

{ index: 617284, steps: 17 }
{ index: -1, steps: 20 }

Each step halves the search range

  1. Look at the middle itemequal → found
  2. Target is biggerdiscard the left half
  3. Target is smallerdiscard the right half
  4. Range emptynot found → -1

Practice

Try it yourself

  1. Sort these by score high→low, and alphabetically on ties: Asha 82, Ravi 90, Zoya 82.

    Show solution
    const rows = [["Asha", 82], ["Ravi", 90], ["Zoya", 82]];
    const ranked = rows.toSorted(([n1, s1], [n2, s2]) => s2 - s1 || n1.localeCompare(n2));
    console.log(ranked.map(([n, s]) => `${n} ${s}`).join(", "));

    Output

    Ravi 90, Asha 82, Zoya 82
  2. Find the second-largest distinct number in [5, 9, 9, 3, 7].

    Show solution
    const distinct = [...new Set([5, 9, 9, 3, 7])].toSorted((a, b) => b - a);
    console.log(distinct[1]);

    Output

    7

Quick check

Why does [10, 9, 1].sort() give [1, 10, 9]?

Without a comparator, items are converted to strings and compared by character codes.

What is the quickest way to remove duplicate primitives?

[...new Set(arr)]

What does binary search require?

A sorted array; it then finds items in O(log n) steps.

Summary

  • Always pass a comparator: a - b for numbers, localeCompare for text.
  • Chain keys with ||; use toSorted to avoid mutating.
  • Set for unique values, Object.groupBy for grouping, binary search for sorted lookups.

Interview practice: JavaScript arrays, objects and ES6 interview questions.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links