Skip to content
Codewilds

Lesson 17 of 34 · Arrays

JavaScript Array find, some, every and sort

medium20 XP3 min read

map, filter and reduce transform arrays. But often you have a simpler question: Where is the first boss above level 50? Is anyone in the party poisoned? Did every player finish the quest? Who's at the top of the leaderboard?

JavaScript has a method for each of these questions, plus one famous trap you need to know about.

find and findIndex

find returns the first item for which your callback returns true, or undefined if there's none:

const levels = [3, 18, 7, 25];

console.log(levels.find((level) => level > 10)); // 18
console.log(levels.find((level) => level > 99)); // undefined

findIndex does the same but returns the item's index, or -1 when nothing matches:

console.log(levels.findIndex((level) => level > 10)); // 1

Unlike filter, find stops at the first match and returns a single item, not an array. There are also findLast and findLastIndex, which search from the end.

some and every

These two return a boolean:

  • some returns true if at least one item passes the test.
  • every returns true if all items pass the test.
const hp = [40, 0, 75];

console.log(hp.some((value) => value === 0)); // true: someone is down
console.log(hp.every((value) => value > 0));  // false: not everyone is standing

Both stop early as soon as the answer is known. One edge case to remember: on an empty array, some returns false and every returns true ("all zero items passed").

sort and the default sort trap

sort puts the items in order. With strings, the default works as you'd expect:

const heroes = ["Linus", "Ada", "Grace"];
heroes.sort();
console.log(heroes); // [ 'Ada', 'Grace', 'Linus' ]

With numbers, the default does something surprising:

const scores = [100, 25, 3];
scores.sort();
console.log(scores); // [ 100, 25, 3 ] (not sorted by value!)

By default, sort converts items to strings and compares them character by character, and "1" comes before "2" and "3". To sort numbers, pass a compare function. It receives two items a and b and returns a negative number if a should come first, a positive number if b should come first, or 0 to keep their order:

scores.sort((a, b) => a - b); // ascending:  [ 3, 25, 100 ]
scores.sort((a, b) => b - a); // descending: [ 100, 25, 3 ]

For strings in a human-friendly order (accents, mixed case), use localeCompare: names.sort((a, b) => a.localeCompare(b)).

sort changes the original array

Unlike map and filter, sort mutates the array it's called on. If you need to keep the original, sort a copy. Modern JavaScript has toSorted, which returns a sorted copy:

const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);
console.log(sorted);   // [ 1, 2, 3 ]
console.log(original); // [ 3, 1, 2 ]

In older code you'll see the same idea written as original.slice().sort(...).

Common mistakes

  • Sorting numbers without a compare function, which gives alphabetical order.
  • Forgetting that sort mutates. Another part of your program may still be using the original order.
  • Using find's result without checking it. If nothing matched, you get undefined, and undefined.name throws a TypeError.
  • Using filter(...).length > 0 instead of some. It works, but some is clearer and stops at the first match.

Assignment

Write four functions:

  1. findFirstOver(numbers, limit) returns the first number greater than limit, or undefined if there isn't one. findFirstOver([3, 8, 12, 20], 10) → 12.
  2. hasNegative(numbers) returns true if at least one number is below zero. hasNegative([4, -1, 7]) → true.
  3. allPassed(scores, passMark) returns true if every score is at least passMark. allPassed([70, 85, 90], 60) → true.
  4. sortedHighToLow(numbers) returns a new array with the numbers sorted from highest to lowest. It must not change the original. sortedHighToLow([5, 100, 20, 1]) → [100, 20, 5, 1].

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Sorting and searching lists in other languages

Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.

Lesson last updated on .

Write code ↓
JavaScript+20 XP

Lesson 17 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.