Prefer chaining methods back to back than creating new every transformation
const newArr = []; newArr .filter(x => x === true) .map(el => el)
/* Filter */ const filteredItems = items.filter( item => { return item.price <= 100; }); /* Map */ const itemNames = items.map( item => { return item.name; }); /* Find */ const foundItem = items.find( item => { return item.name === "book"; }); /* forEach - do something for every single element in array */ items.forEach( item => { console.log(item.name); }); /* Same - returns boolean for whether any element is matching */ const expensiveItem = items.some( item => { return item.price <= 100; }); /* Every - returns boolean when every single item meets the condition */ const lessThanHundred = items.every( item => { return item < 100; }); /* Reduce */ const total = items.reduce( (carryover, item) => { return item.price + carryover; }, 0); // 0 is the starting value /* Includes - boolean for whether array contains a value */ const includesTwo = items.includes(2);
.forEach()
forEach
method calls a function once for each element in array in order
const array1 = ['a', 'b', 'c']; array1.forEach(element => console.log(element)); // a b c
Example of Creating New Modified Array
const numbers = [1,2,3]; const newNumbers = []; numbers.forEach((x) => newNumbers.push(x*2)); console.log(newNumbers); // [2,4,6]
indexOf()
and forEach()
to remove duplicates from Arrayfunction removeDup(arr) { const result = []; // iterate through passed array, check if the index is its first occurence of item arr.forEach((item, index) => { if (arr.indexOf(item) == index) { result.push(item) } }); return result }
.from()
Static method creates a new, shallowed-copied Array
instance from an iterable or array-like object
Map
, Set
length
property and indexed elements
/* String iterated as array */ Array.from('foo'); // ["f", "o", "o"] /* Array iterated and modified */ Array.from([1, 2, 3], (x) => x*2); // [2, 4, 6]
When dealing with async iterables, use Array.fromAsync()
.isArray()
Determines whether the passed value in an array
in boolean
Array.isArray([1, 2, 3]) // true Array.isArray({foo: 123}) // false Array.isArray('foobar') // false Array.isArray(undefined) // false
.join()
creates and returns a new string by concatenating all of the elements in the array
const elements = ['Fire', 'Air', 'Water']; console.log(elements.join()); // "Fire,Air,Water" console.log(elements.join('')); // "FireAirWater" console.log(elements.join('-')); // "Fire-Air-Water" console.log(elements.join(', ')); // "Fire, Air, Water"
.length()
returns number of elements in an array
x = ["one", "two"].length; // 2
let lastIndex = array.length-1; let lastElement = array[lastIndex];
.some()
Tests whether at least one element in the array passes the test implemented by the provided function
boolean
const array = [1, 2, 3, 4, 5]; // Checks whether an element is even const isEven = (el) => el % 2 === 0; array.some(isEven); // true