Iterators in js

Yoseob Shin·2022년 3월 30일
0

javascript

목록 보기
12/24
post-thumbnail
post-custom-banner

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

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) => { /* ... */ })
  • index parameter는 여기서 반복문 loop 에서 현재 element.
  • array parameter는 forEach()를 호출한 현재 array.
    callbackFn
  • thisArg Optional: Value to use as this when executing callbackFn. (몰랐음...)
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

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'

The .filter() Method

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']
  • From above, word.length < 6; is the condition in the callback function. Any word from the words array that has fewer than 6 characters will be added to the shortWords array.

The .findIndex() Method

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

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.

Different Usage of .reduce()

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()

Bonding arrays contained in an array of objects using the spread operator and initialValue

// 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'
// ]

Arr.sum() / Arr.every()

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.

Review

  • .forEach() is used to execute the same code on every element in an array but does not change the array and returns undefined.
  • .map() executes the same code on every element in an array and returns a new array with the updated elements.
  • .filter() checks every element in an array to see if it meets certain criteria and returns a new array with the elements that return truthy for the criteria.
  • .findIndex() returns the index of the first element of an array that satisfies a condition in the callback function. It returns -1 if none of the elements in the array satisfies the condition.
  • .reduce() iterates through an array and takes the values of the elements and returns a single value.
  • All iterator methods take a callback function, which can be a pre-defined function, a function expression, or an arrow function.
  • You can visit the Mozilla Developer Network to learn more about iterator methods (and all other parts of JavaScript!).
    Instructions
  • If you want to challenge yourself:

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.

profile
coder for web development + noodler at programming synthesizers for sound design as hobbyist.
post-custom-banner

0개의 댓글