[TIL] Iteration & Arrays

eunnb05·2022년 5월 7일
0

Today I learned [TIL]

목록 보기
1/3

There are multiple ways to iterate through an array, other than the familiar for loop.

1. forEach() method

const options = ['a', 'b', 'c', 'd'];

options.forEach(item => console.log(`You have selected option ${item}.`));

As you can see above, the forEach() method takes a callback function as an argument.

"A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished." - w3schools

The forEach() method will execute this function for each element in the array "options", and it will do it without modifying the original array.
One thing to remember is that forEach() does not have a return value. If you try to get a return value, it will result in undefined.

let order = options.forEach(item => console.log(`You have selected option ${item}.`));
// "You have selected option a."
// "You have selected option b."
// "You have selected option c."
// "You have selected option d."

console.log(options);
// ["a", "b", "c", "d"]

When to use ?

  • To log errors in a code.
  • To mutate the original array or object.

2. map() method

The map() method also calls a function on every element of an array, but this time, it transforms the elements and creates a new array for the values.

Here is an example :

const numbers = [1, 4, 9];
const squareRoots = numbers.map(num => Math.sqrt(num);

console.log(numbers);          // [1, 4, 9]
console.log(squareRoots);      // [1, 2, 3] 

Math.sqrt(num) iterates through each number of "numbers" and empties each result in the new array.

When to use ?

  • To non-destructively update objects with new key pair values.
  • To reformat objects.
  • To change the values of an array.

3. filter() method

Iterates thorugh an array returning all elements that meet the criteria specified in the callback function.

let numbers = [4, 2, 1, 7, 10, 9, 6, 3, 5, 8];

let greaterThanFive = numbers.filter(num => num >= 5);

console.log(greaterThanFive);     // [7, 10, 9, 6, 8]

The array above is comprised of the numbers 1 to 10 in a disorderly manner. Using filter() we can return an array that only has the numbers greater and equal to 5.

filter can also be used with objects :

const menu = {
	{appetizer: 'hummus dip', entree: 'avocado wrap', dessert: 'cake'},
    {appetizer: 'salad', entree: 'chicken sandwich', 'dessert: 'ice cream'},
    {appetizer: 'chips', 'chicken sandwich', 'dessert: 'cake'}
};

const cake = orders.filter(order => order.dessert === 'cake');

console.log(cake); 
// [{appertizer: 'hummus dip', entree: 'avocado wrap', dessert: 'cake'}, {appetizer: 'chips', entree: 'chicken sandwich', dessert: 'cake'}]

The cake variable returns with the two objects that include cake on its menu.

When to use ?

  • To loop through complex arrays using a callback function and return all elements that meet the criteria.
  • To filter duplicates out of an array.
  • To find all similar objects in an array.

4. find() method

find() passes a callback function to each element of an array until the element meets the criteria. The iteration will stop immediately when it meets the first element that meets the criteria.

Let's bring back our menu :

const menu = {
	{appetizer: 'hummus dip', entree: 'avocado wrap', dessert: 'cake'},
    {appetizer: 'salad', entree: 'chicken sandwich', 'dessert: 'ice cream'},
    {appetizer: 'chips', 'chicken sandwich', 'dessert: 'cake'}
};

const cake = orders.find(order => order.dessert === 'cake');
// {appetizer: 'hummus dip', entree: 'avocado wrap', dessert: 'cake'}

The variable cake now equals the first option of the menu.

When to use ?

  • To loop through an array using a complex callback function.
  • To let other coders understand that you are looking for only one element that meets the criteria.

5. reduce() method

reduce() transforms an array but reduces it into a singular value. The function passes in the return value from the calculation on the preceding element.

It takes two parameters:

  • Accumulator argument : the accumulated value for the previously returned value in the loop.
  • Current value : the current value in the array that is being run through the callback function.
const array = [1,2,3,4,5];

// 0 + 1 + 2 + 3 + 4 + 5
const initialValue = 0;
const sumTotal = array.reduce(
	(accumulator, currentValue) => accumulator + currentValue, initialValue
);

console.log(sumTotal);       // 15

If the initial value is specified, the calculation will start from that value.

When to use ?

  • To transform an array into a singular value.
  • To concatenate and flatten arrays.
  • To count instances of values in objects.

6. for...in statement

The for...in statement is commonly used with objects than arrays, because it does not keep the elements in index order.

Here is an example :

const menu = {
	appetizer: 'hummus dip', 
    entree: 'chicken sandwich', 
    dessert: 'cake'
}

for (const key in menu) {
	console.log(`for your ${key}, we will be serving you a ${menu[key]}.`)
}

// for you appetizer, we will be serving you a hummus dip.
// for you entree, we will be serving you a chicken sandwich.
// for you dessert, we will be serving you a cake.

for...in looks very similar to the for loop, except it has a different syntax:
for (variable in object) { statement }.

key is the variable. The variable can be any variable name. menu is the object we want to loop through. The for...in statement above, logs in the console three senteces, each with the name object's property name and its value.

When to use ?

  • To quickly pull properties from an object.

7. for...of statement

for...of statement takes into account the order of the elements of a collection; therefore, it is used more frequently with arrays.

Like forEach() method, it does not create a new array with the outcome.

const menuItems = ['ceasar salad', 'hummus dip', 'falafel'];

for (const item of menyItems) {
	if (item.length === 0) break
    console.log(`you ordered a ${item} today.`)
}

// you ordered a ceasar salad today.
// you ordered a hummus dip today.
// you ordered a falafel today.

When to use ?

  • To quickly run through elements in an array without needing to create a new array with the results.

0개의 댓글