4 min read
•Question 38 of 50mediumWhat are advanced Array methods?
Understanding find, some, every, and other array methods.
What You'll Learn
- Finding elements
- Testing conditions
- Flattening and filling
Finding Elements
code.jsJavaScript
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' }
];
// find - returns first match
const user = users.find(u => u.id === 2);
// { id: 2, name: 'Jane' }
// findIndex - returns index
const index = users.findIndex(u => u.id === 2);
// 1
// includes - check existence
[1, 2, 3].includes(2); // true
// indexOf - find index
[1, 2, 3].indexOf(2); // 1Testing Conditions
code.jsJavaScript
const numbers = [1, 2, 3, 4, 5];
// some - at least one matches
numbers.some(n => n > 3); // true
numbers.some(n => n > 10); // false
// every - all must match
numbers.every(n => n > 0); // true
numbers.every(n => n > 3); // falseFlattening
code.jsJavaScript
// flat - flatten nested arrays
const nested = [1, [2, [3, [4]]]];
nested.flat(); // [1, 2, [3, [4]]]
nested.flat(2); // [1, 2, 3, [4]]
nested.flat(Infinity); // [1, 2, 3, 4]
// flatMap - map then flatten
const sentences = ['Hello world', 'Hi there'];
sentences.flatMap(s => s.split(' '));
// ['Hello', 'world', 'Hi', 'there']Filling and Creating
code.jsJavaScript
// fill
new Array(5).fill(0); // [0, 0, 0, 0, 0]
[1, 2, 3].fill(0, 1); // [1, 0, 0]
// Array.from
Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
Array.from({ length: 5 }, (_, i) => i);
// [0, 1, 2, 3, 4]
// Array.of
Array.of(1, 2, 3); // [1, 2, 3]