Array.map()

Array.map() updates each value in the given Array based on the passed conversion function and returns a new Array of the same length. It takes a callback function as an argument to perform the conversion process.

let newArray =oldArray.map((value,index,array)=>{
  ...
});

Copy the code

One way to help remember maps: Morph Array piece-by-piece You can use map instead of a for-each loop to iterate over and apply conversion functions to each value. This method is useful when you want to update an array while preserving the original values. It does not potentially remove any values (the Filter method does), nor does it compute a new output (as reduce does). Map allows you to change arrays one by one. Let’s look at an example:

[1,4,6,14,32,78]. Map (val =>val *10) // result is: [10, 40, 60, 140, 320, 780]Copy the code

Mmbiz. Qpic. Cn/mmbiz_jpg/m…

Array.filter()

The quick and useful method array.filter () comes in handy when we want to filter an Array of values to another Array, with each value in the new Array passing a specific check. Similar to a search filter, a filter filters out values based on passed parameters.

For example, if you have an array of numbers and want to filter out values greater than 10, you can write:

[1,4,6,14,32,78]. Filter (val =>val >10) // the result is: [14, 32,78]Copy the code

The filter method, however, returns only the true value. So if all values are checked as specified, the length of the result will be less than or equal to the original array.

Think of a filter as a funnel. Some of the mixture passes through into the result, while others are left behind and discarded.Copy the code

Mmbiz. Qpic. Cn/mmbiz_jpg/m…

Suppose a pet training school has a small class of four dogs, and all the dogs in the school go through various challenges and then take a graded final exam. We represent these dogs with an array of objects:

const students =[
{
    name:"Boops",
    finalGrade:80
},
{
    name:"Kitten",
    finalGrade:45
},
{
    name:"Taco",
    finalGrade:100
},
{
    name:"Lucy",
    finalGrade:60
}
]
Copy the code

Dogs get a fancy certificate if they score more than 70 on a final exam; If not, they have to rebuild. To know how many certificates are printed, write a method that returns the dog that passed the test. Instead of writing a loop through every object in a group, we can simplify the code with filter!

const passingDogs = students.filter((student)=>{
   return
      student.finalGrade >=70
})
Copy the code

Array.reduce()

The reduce() method takes an array as input and returns a value. This is interesting. Reduce takes a callback function that takes an accumulator (the sum of each segment of the array, which grows like a snowball), the current value, and the index. Reduce also accepts an initial value as a second argument:

let finalVal = oldArray.reduce((accumulator,currentValue,currentIndx
,array)=>{
...
}),initalValue;
Copy the code

Mmbiz. Qpic. Cn/mmbiz_jpg/m…

Write a frying function and a list of ingredients:

const ingredients = ['wine'.'tomato'.'onion'.'mushroom']
// a cooking function
const cook = (ingredient) => {
  return `cooked ${ingredient}`}Copy the code

If we want to make a sauce out of these ingredients (just kidding), reduce()!

const wineReduction = ingredients.reduce((sauce, item)=>{
 return  sauce += cook(item) +', '
},' ')
// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom, "
Copy the code

The initial value (” in this case) is important and determines that the first ingredient will be ready for cooking. The output here is not very reliable, so be careful when cooking yourself. Here’s an example of what I’m talking about:

const wineReduction = ingredients.reduce((sauce, item)=>
{
   return sauce += cook(item) + ', '
})
// wineReduction = "winecooked tomato, cooked onion, cooked mushroom, "
Copy the code

Finally, to ensure that there is no extra whitespace at the end of the new string, we can pass indexes and arrays to perform the conversion:

const
 wineReduction 
=
 ingredients
.
reduce
((
sauce
,
 item
,
 index
,
 array
)
 
=>
 
{
  sauce 
+=
 cook
(
item
)
  
if
 
(
index 
<
 array
.
length 
-
 
1
)
 
{
    sauce 
+=
 
', '
  
}
  
return
 sauce
},
 
' '
)

// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"
Copy the code

You can use the ternary operator, template strings, and implicit returns to write more succinctly (one line!). :

const
 wineReduction 
=
 ingredients
.
reduce
((
sauce
,
 item
,
 index
,
 array
)
 
=>
 
{
  
return
 
(
index 
<
 array
.
length 
-
 
1
)
 
?
 sauce 
+=
 
`${cook(item)}, `
 
:
 sauce 
+=
 
`${cook(item)}`},' '
)

// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"
Copy the code

Array​.prototype​.flatMap()

The flatMap() method first maps each element using a mapping function and then compresses the result into a new array. It is almost identical to a map and a flat with a depth value of 1, but flatmaps are usually slightly more efficient when combined into one method.

grammar

var new_array = arr.flatMap(functionCallback (currentValue[, index[, array]]) {}[, thisArg])Copy the code

parameter

Callback can generate a function for elements in a new array, passing in three arguments:

CurrentValue The element currently being processed in the array index Optional Optional. The index of the current element being processed in the array. Array Optional Optional. The map array to be called is thisArg optional optional. The this value used when the callback function is executed.

The return value

A new array where each element is the result of a callback function and the structure depth is 1.

The sample

The Map and flatMap

var arr1 = [1, 2, 3, 4]; arr1.map(x => [x * 2]); // [[2], [4], [6], [8]] arr1.flatMap(x => [x * 2]); FlatMap (x => [[x * 2]]); flatMap(x => [[x * 2]]); [[2], [4], [6], [8]]Copy the code
let arr = ["It's a nice day.".""."Good morning."]

arr.map(s => s.split("")) / / [["Today"."Day"."Day"."Gas"."No"."Wrong"], [""], ["Early"."On"."Good"]]

arr.flatMap(s => s.split(' ')); / / /"Today"."Day"."Day"."Gas"."No"."Wrong".""."Early"."On"."Good"]
Copy the code

Equivalent operations

Reduce and concat

var arr1 = [1, 2, 3, 4]; arr1.flatMap(x => [x * 2]); / / equivalent to arr1. Reduce ((acc, x) = > acc. Concat () [x * 2], []); // [2, 4, 6, 8]Copy the code