Array Methods Javascript Flashcards
forEach Method
forEach method executes a provided function once for each array element
forEach will go through each number in the array and run the function.
const array1 = [‘a’, ‘b’, ‘c’];
array1.forEach(element => console.log(element));
// expected output: "a" // expected output: "b" // expected output: "c"
Map Method
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Map() takes the array , does the functions and puts it into a new array.
const array1 = [1, 4, 9, 16];
// pass a function to map const map1 = array1.map(x => x * 2);
console.log(map1); // expected output: Array [2, 8, 18, 32]
Filter Method
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
const words = [‘spray’, ‘limit’, ‘elite’, ‘exuberant’, ‘destruction’, ‘present’];
const result = words.filter(word => word.length > 6);
console.log(result); // expected output: Array ["exuberant", "destruction", "present"]
Find Method
The find() method returns the value of the first element in the provided array that satisfies the provided testing function.
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found); // expected output: 12
Reduce Method
Reduce () method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4 console.log(array1.reduce(reducer)); // expected output: 10
// 5 + 1 + 2 + 3 + 4 console.log(array1.reduce(reducer, 5)); // expected output: 15
Some Method
Some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
const array = [1, 2, 3, 4, 5];
// checks whether an element is even const even = (element) => element % 2 === 0;
console.log(array.some(even)); // expected output: true
Every Method
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold)); // expected output: true