JavaScript Iterators #
Called on arrays to return values.
Methods #
.filter() #
Returns an array after filtering out some elements.
Callback function used should return true or false. true elements are added to the returned array.
const someArr = [1, 2, 3]
const newArr = someArr.filter(
num => {
return num > 1;
}
)
.findIndex() #
Find the index of an element in an array based on some condition. Returns the first element that is true.
const someArr = [1, 2, 3]
const newArr = someArr.findIndex(
num => {
return num > 2;
}
)
If nothing matches, a -1 is returned.
.forEach() #
Run the same code on each element of an array.
const someArr = [1, 2, 3]
someArr.forEach(
function(arrItem) {
console.log(arrItem * arrItem);
}
)
Can also be expressed as an arrow function.
.map() #
Takes an array, returns an array.
const someArr = [1, 2, 3];
const squaredArr = someArr.map(
number => { // number is a parameter
return number * number
}
);
.reduce() #
Takes in array, returns a single value.