One tool at our disposal is the for loop. However, we also have access to built-in array methods which make looping easier.
The built-in JavaScript array methods that help us iterate are called iteration methods, at times referred to as iterators. Iterators are methods called on arrays to manipulate elements and return values.
The forEach() method executes a provided function once for each array element.
.forEach() takes an argument of callback function. Remember, a callback function is a function passed as an argument into another function.
.forEach() loops through the array and executes the callback function for each element. During each execution(실행중), the current element is passed as an argument to the callback function.
Can define a function beforehand to be used as callback function
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
// Iterate over fruits below
fruits.forEach(fruit => console.log(`I want to eat a ${fruit}`));
// I want to eat a mango
//I want to eat a papaya
//I want to eat a pineapple
//I want to eat a apple
순수 자바스크립트로 forEach 로직을 풀이하면...
function theForEach(theArray, theCallBackFunction){
for (let i = 0; i < theArray.length; i++){
theCallBackFunction(theArray[i]);
}
}
const myArray = [1, 2, 3];
const myCallBack = element => {
console.log(element);
}
theForEach(myArray, myCallBack);
// Arrow function
forEach((element) => { /* ... */ })
forEach((element, index) => { /* ... */ })
forEach((element, index, array) => { /* ... */ })
function Counter() {
this.sum = 0
this.count = 0
}
Counter.prototype.add = function(array) {
array.forEach(function countEntry(entry) {
this.sum += entry;
++this.count;
}, this);
};
const obj = new Counter();
obj.add([2, 5, 9]);
console.log(obj.count); // 3
console.log(obj.sum); // 16
Since the thisArg parameter (this) is provided to forEach(), it is passed to callback each time it's invoked. The callback uses it as its this value.
The map() method creates/return a new array populated with the results of calling a provided function on every element in the calling array. (MDN)
Array 내용물을 수정하거나 업데이트 할때 자주 쓰인다.
map(function(element) { /* ... */ })
map(function(element, index) { /* ... */ })
map(function(element, index, array){ /* ... */ })
map(function(element, index, array) { /* ... */ }, thisArg
const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];
// Create the secretMessage array below
const secretMessage = animals.map(animal => animal[0]); // ['H', 'e','l','l','o','W','o','r','l','d']
console.log(secretMessage.join('')); // 'HelloWorld'
Like .map(), .filter() returns a new array. However, .filter() returns an array of elements after filtering out certain elements from the original array.
The callback function for the .filter() method should return true or false depending on the element that is passed to it. The elements that cause the callback function to return true are added to the new array.
const words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door'];
const shortWords = words.filter(word => {
return word.length < 6;
});
console.log(shortWords); // Output: ['chair', 'music', 'brick', 'pen', 'door']
We sometimes want to find the location of an element in an array. That’s where the .findIndex() method comes in!
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.
// Inline callback function
findIndex(function(element) { /* ... */ })
findIndex(function(element, index) { /* ... */ })
findIndex(function(element, index, array){ /* ... */ })
findIndex(function(element, index, array) { /* ... */ }, thisArg)
The .reduce() method returns a single value after iterating through the elements of an array, thereby reducing the array.
The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).
// Inline callback function
reduce(function(previousValue, currentValue) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ }, initialValue)
If initialValue is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0.
Flatten an array of arrays
let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
( previousValue, currentValue ) => previousValue.concat(currentValue),
[]
Counting duplicates, or instances of value in object.
Grouping objects by a property
Replace .filter().map() with .reduce()
// friends - an array of objects
// where object field "books" is a list of favorite books
let friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'The Shining'],
age: 18
}]
// allbooks - list which will contain all friends' books +
// additional list contained in initialValue
let allbooks = friends.reduce(function(previousValue, currentValue) {
return [...previousValue, ...currentValue.books]
}, ['Alphabet'])
// allbooks = [
// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
// 'Romeo and Juliet', 'The Lord of the Rings',
// 'The Shining'
// ]
Both methods return boolean. However, sum() methods returns true if at least one element passes user-supplied test(condition) whereas every() only returns true if every single elements satisfies the given condition by user in callback function.
Define a callback function before you use it in a iterator.
Chain two iteration methods on the same array.
Use the optional arguments in an iterator to include the index or the entire array. (Check out MDN’s Array iteration methods page for more information)
Use .reduce() to take a multi-layered array and return a single layer array from scratch.