Sub topic 3
Finding Elements and Testing Conditions
This chapter assumes you already know arrow functions, the (element, index, array) callback signature, and the difference between mutating and non-mutating methods.
Searching and Testing
Each search method returns a different kind of result:
| Method | Returns |
|---|---|
| `find` / `findLast` | The first or last matching element, or `undefined` |
| `findIndex` | The position of the first match, or `-1` |
| `indexOf` / `includes` | A position or a boolean, using strict equality |
| `some` / `every` | A boolean for "any match" or "all match" |
const users = [
{ name: 'Ana', age: 31 },
{ name: 'Ben', age: 17 },
{ name: 'Cleo', age: 24 }
];
console.log(users.find(u => u.age < 18)); // { name: 'Ben', age: 17 }
console.log(users.findIndex(u => u.name === 'Cleo')); // 2
console.log(users.some(u => u.age < 18)); // true
console.log(users.every(u => u.age > 10)); // true
console.log([1, 2, 3].includes(2)); // trueSorting with Comparators
sort changes the array in place. Without a comparator it compares elements as strings. A comparator returns a negative number to put a first, a positive number to put b first, or zero to keep their order. toSorted (ES2023) returns a sorted copy and leaves the original alone.
const nums = [10, 1, 5];
console.log([...nums].sort()); // [1, 10, 5] (compared as strings)
console.log(nums.toSorted((a, b) => a - b)); // [1, 5, 10]
console.log(nums); // [10, 1, 5] (unchanged)Copying and Combining
const original = [1, 2, 3];
console.log([...original]); // [1, 2, 3]
console.log(original.concat([4, 5])); // [1, 2, 3, 4, 5]
console.log(original.with(0, 99)); // [99, 2, 3]
console.log(original); // [1, 2, 3]slice, toReversed, and toSpliced also return new arrays.
Chaining into Pipelines
Methods that return arrays can be chained, which reads like a series of steps:
const orders = [
{ id: 1, total: 40, paid: true },
{ id: 2, total: 15, paid: false },
{ id: 3, total: 25, paid: true }
];
const paidTotal = orders
.filter(order => order.paid)
.map(order => order.total)
.reduce((sum, total) => sum + total, 0);
console.log(paidTotal); // 65Flattening and Array.from
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat()); // [1, 2, [3, [4]]]
console.log(nested.flat(Infinity)); // [1, 2, 3, 4]
console.log(['hello world', 'hi'].flatMap(s => s.split(' '))); // ['hello', 'world', 'hi']
console.log(Array.from({ length: 4 }, (_, i) => i * 2)); // [0, 2, 4, 6]
console.log(Array.of(7)); // [7]
console.log(Array(7).length); // 7 (seven empty slots)Edge Cases
try {
[].reduce((a, b) => a + b);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log([].reduce((a, b) => a + b, 0)); // 0Exercise
Why does [10, 1, 5].sort() return [1, 10, 5], and how would you get a numerically sorted copy without changing the original?
Show answer
With no comparator, sort converts elements to strings and compares them, so "10" comes before "5". Use arr.toSorted((a, b) => a - b) to get a sorted copy.