[ES6] Understand the use of map, forEach, filter and find with arrow functions in JavaScript

If you are a person who is just learning JavaScript, you may find it easy to write arrow functions. But if you were used to writing JavaScript before the arrow function appeared, then before you adapt, every time you encounter an arrow function, you may need to search the syntax of the arrow function on the Internet or organize your notes. I believe that many people have such experiences. However, once you get used to writing arrow functions, you can write so much cleaner code that you might forget about the traditional way later.
In this article, we will explain how to use arrow functions and map, forEach, find, and filter functions to help you master the writing method of arrow functions and the usage of each function.

    • 1 How to write arrow functions
    • 2 Map function usage
    • 3 ForEach function use
    • 4 use of find function
    • 5 filter function usage
    • 6 reduce function use

1 How to write arrow functions

The processing content is the same, but if the current function is written with an arrow function, it will be as follows.

let add = (a, b) => {<!-- -->
  console.log(a + b)
}

Furthermore, if there is only one line of code in curly braces like console.log, it can also be written like this.

let add = (a, b) => console. log(a + b)

If you don’t want to use arrow functions without parameters:

let hello = function(){<!-- -->
    console.log('Hello World!')
}

How do I write a function that returns a value, you can see the code description below.

let add = (a, b) => {<!-- -->
  return a + b
}
// return can also be written as follows
let add = (a, b) => a + b
// Parentheses can be omitted if there is only one parameter.
let add = a => a + 20

By using arrow functions in this way, many parts can be omitted and the code shortened.

2 Map function usage

The map function is a method of manipulating and processing arrays, and it can traverse each element in the array. By using it, we can easily operate on arrays. The actual operation is easier to understand than the text explanation, so let’s take a look at how to use the map function to manipulate the array.

? For example, if you have a numeric array price and you want to multiply each element by 1.1, then you can use the map function to achieve this operation. In the callback function of the map function, we multiply each element of the array by 1.1 and put the result into a new array. In this way, each element of the new array corresponds to the operated element in the original array, but their values are multiplied by 1.1.

? It is worth noting that the elements in the manipulated original array have not been changed, they still maintain the original value. Instead, each element in the new array is 1.1 times the corresponding element in the original array. Using the map function for this kind of array operation allows us to easily process elements in the array in batches, improving code efficiency and readability.

const price = [100,500,1000]
tax_price = price. map(function(value){<!-- -->
  return value*1.1
})
console.log(tax_price)
>[110, 550, 1100]

Use arrow function abbreviations

You can use the arrow function you learned before to shorten the writing of the callback function, as follows:

javascriptCopy codeconst prices = [10, 20, 30];
const newPrices = prices. map(price => price * 1.1);

In the above code, we use arrow functions to define callback functions. Arrow functions have only one parameter in their parameter list, so we can omit the parentheses. At the same time, the return value of the arrow function is a single-line expression, so the curly braces and the return keyword can also be omitted. In this way, we can multiply each element in the array by 1.1 and generate a new array with one line of concise code. Using arrow functions allows us to write code more concisely, improving the readability and maintainability of the code.

In the callback function of the Map function, in addition to the value of the element, another parameter can be used to indicate the index of the current element. This parameter is usually called “index” or “idx”. Using the index parameter can directly access and manipulate the elements in the array, so that the map function operation is more flexible and efficient.

const price = [100,500,1000]
tax_price = price. map( (value,index) => value*1.1*index )
console.log(tax_price);
[ 0, 550, 2200 ]

3 ForEach function use

ForEach function operation is similar to map, which can be used to process each element in the array individually. **The map function has a return value, but the forEach function does not. **Note that the forEach function differs from map in that the forEach function does not return a value. Since there is no return value, we create a tax_price array and put the recalculated value after traversal into the tax_price array.

const price = [100,500,1000]
tax_price = []
price.forEach(function(value){<!-- -->
  tax_price.push(value * 1.08)
})
console.log(tax_price);

Use arrow function abbreviations

price.forEach(value => tax_price.push(value * 1.08))

forEach executes traversal array object is a function
Functions can be placed in the elements of a JavaScript array, we use forEach to iterate through the functions in the array, and these functions can be executed as follows.

let z_world = () => console.log('Hello World')
let z_javascript = () => console. log('Hello JavaScript')
const hello = [z_world, z_javascript]
hello. forEach(value => value())

forEach index

The forEach function can not only get the elements of the array, but also get the index of the array. The parameter index is the index of the array, and using index in the method is to obtain the index reference of the array.

price.forEach(function(value,index){<!-- -->
  console.log(value + " " + price[index])
})
//When using the index, using the arrow function will look like this.
price.forEach((value,index) => console.log(value + " " + price[index]))

If you don’t need to return a value, the result is the same whether you use map or forEach. The main difference between them is that map has a return value, while forEach has no return value.

4 find function use

The find function is to find elements that meet certain conditions in the array, and it can only retrieve the first element that meets the conditions. Finding elements that meet certain conditions in an array is a common operation, and we can use the find function of the array to achieve it. This function receives as a parameter a callback function that checks whether each element in the array satisfies a certain condition. Returns the element if the condition is met, otherwise returns undefined. It should be noted that the find function can only retrieve the first element that meets the condition, but not all elements that meet the condition.

const price = [100, 500, 1000]
over = price. find(function(value){<!-- -->
return value > 400
})
console. log(over)
>500

There are 500 and 1000 that meet the above conditions, but only 500 are retrieved. Since 500 is the first element greater than 400, the find function returns 500 and assigns it to the “over” variable. The final output is 500.

Use arrow function abbreviations

over = price. find(value => value > 400)

5 filter function use

The find function retrieves only one element that meets the condition, while the filter (filter function) retrieves all elements that meet the condition.

const price = [100, 500, 1000]
over = price. filter(function(value){<!-- -->
return value > 400
})
console. log(over)
>[500,1000]

Use arrow function abbreviations

over = price. filter(value => value > 400)

The main difference between find and filter is that find has the first element that meets the conditions, and filter returns the element that meets the conditions.

6 reduce function usage

Some people may not be familiar with the use of the reduce function, because it is not as commonly used as other common loop functions. However, the reduce function is very useful when dealing with aggregations of array elements.

The syntax of the reduce function is as follows:

array.reduce((accumulator, currentValue) => {<!-- -->
  // aggregation logic
}, initialValue);

It should be noted that the reduce function can receive an initial value (initialValue), or omit this initial value. One of the most common use cases for the reduce function is to sum an array.

For example, suppose we have an array “test” and we want to sum all the elements in it. We can use the reduce function to achieve, the code is as follows:

const test = [10,20,30]
const sum = test.reduce(((pre, cur) => pre + cur),100)
console. log(sum)

If an initial value of 100 is given, then on the first iteration, pre will contain 100 and cur will contain the first value of the test array, 10. The result of 100 + 10 will be the next predicted value. This is the first loop. The second iteration will set pre to the previous result of 110, cur will contain the second value of the test array, 20, and the result of 110 + 20 will be the next pre value. The last iteration will be to set pre to the previous result of 130 and cur will contain the third value of the test array, 30. The result of 130 + 30 will be the final return value of 160 from the reduce function.