Iteration methods, iterators = methods called on arrays to manipulate elements and return values.
.forEach() always returns an 'undefined'.
.map() takes an argument of a callback function and returns a new array.
.filter() returns a new array of elements after filtering out certain elements from the original array. The callback function should return true or false depending on the element that is passed to it. Return true --> added to the new array.
.findIndex() will return the index of the first element that evaluates to true in the callback function. Output is -1 when there isn't a single element in the array that satisfies the condition in the callback.
.reduce() method returns a single value after iterating through the elements of an array, reducing the array.
.some() tests whether at least one element in the array passes the test implemented by the provided function. .every() tests wheter ALL elements in the array pass the test implemented by the provided function. (True if array is empty) .includes() whether an array includes a certain value among its entries (true/false)
groceries.forEach(funciton(groceryItem) { //.forEach() takes an argument of callback function, loops through the array and executes the callback function for each element
console.log (' - ' + groceryItem);
});
groceries.forEach(groceryItem => console.log(groceryItem)); //with arrow functions
//.map()
const numbers = [1, 2, 3, 4, 5];
const bigNumbers = numbers.map(number => {
return number * 10;
});
//.filter() method
const words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door'];
const shortWords = words.filter(word => {
return word.length < 6;
});
const jumbledNums = [123, 25, 78, 5, 9];
//findIndex() method
const lessThanTen = jumbledNums.findIndex(num => {
return num < 10;
});
//.reduce() method
const numbers = [1, 2, 4, 10];
const summedNums = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue
})
console.log(summedNums) // Output: 17
// reduce can take an optional second parameter to set an initial value for accumulator (here set to 100)
const numbers = [1, 2, 4, 10];
const summedNums = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue
}, 100) // <- Second argument for .reduce()
console.log(summedNums); // Output: 117
//.some()
var array = [1, 2, 3, 4, 5];
var even = function(element) {
// checks whether an element is even
return element % 2 === 0;
};
console.log(array.some(even));
// expected output: true
//.every()
function isBelowThreshold(currentValue) {
return currentValue < 40;
}
var array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true