Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

ForEach, map, reduce, filter, every, some these six functions to tell about, for every and some I belong to the rare will use, do not know how you ๐Ÿ˜ต


The forEach ๐Ÿคก

ForEach is an ES5 method for manipulating arrays. The main function is to iterate over the elements of an array. The argument is a callback function

Call syntax:

arr.forEach((item, index, array) = >{... })Copy the code

Of the three parameters, the last array parameter is rarely used.

parameter describe
item Array currently traverses the element and must be present
index Optional index of the current element
array Array, optional

ForEach is an enhanced version of the for loop, similar to $.each in jQuery. An error is not reported even for an empty array.

Object elements cannot be traversed directly, but objects can be converted and traversed through conversion methods such as Object.entries or object. values.

Example:

let arr = [1.2.3.'456'.false, { sex: null }]
let obj = { name:'Joe'.age: 40.scroe: 77.isPass: true }

/*********** forEach ***********/
arr.forEach((item, index, objArr) = >{
    console.log(Array element${index} : ${item}`);
}) 
console.log('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --');
Object.values(obj).forEach((item, index, objArr) = >{
    console.log('Object element${index} : ${item}`);
}) 
Copy the code

Results:



The map ๐Ÿค–

Map refers to the map function of the array, not the MAP data structure of ES6.

Map is used in a similar way to forEach, but mainly to create a new array.

  • forEachThe method does not return the result, but rather returnsundefined
  • mapReturns a new array, the original and the new array do not affect each other

Example:

// map generates a new array
let newarr = arr.map((item, index, objArr) = >{
    console.log(Array element${index} : ${item}`);
    return item;
})
arr[1] = 10;  // Change the original array, the new array is not affected
console.log(newarr);
console.log(arr);
Copy the code

Results:

Note:Here, if you’re modifying an object in the original array{sex: null}In thesexValue, the new array newarr will also change accordingly, because the objects in both arrays point to the same storage address.

Although map and forEach are basically the same in terms of traversal, forEach is faster in terms of efficiency because map also returns new arrays, which involves deep copies of arrays.

Therefore, the usage scenarios of the two are different:

  • This is best used when you simply iterate over a number array and only need to use internal elementsforEach
  • If you want to change the value of the data, you can map an array to another array according to some rulemap
  • Of course, in general if there is no very strict performance requirements, actually usemapThis is also a nice higher-order notation


Reduce ๐Ÿ‘พ

The reduce() method performs a reducer function (in ascending order) that you provide on each element in the array, summarizing its results into a single return value

Similar to forEach and map, the callback takes four arguments and returns a cumulative value

arr.reduce((acc, cur, idx, src) = >{...return total;
})
Copy the code
parameter describe
The acc (Accumulator) Accumulator, initial value, or return value at the end of calculation; Not only can you add, you have to
Cur (Current Value) Current value, required
Idx (Current Index) Current index, optional
SRC (Source Array) Array, optional

Because the reduce function is intended to be a summation method, it is desirable that all values in the array be of type number, otherwise errors may occur

Summing traversal (internally conditional judgment of elements) :

let arr = [1.2.3.'456'.false, { sex: null }];
let total = arr.reduce((acc, cur, idx, src) = >{
    let type = typeof cur;
    if(type ! ='number') {
        if (type == 'string'){
            cur = parseInt(cur);
        } else{
            cur = 0; }}console.log('Cumulative value:${acc}, current element:${cur}`);
    return acc + cur;
})
console.log(The array summation is:${total}`);
Copy the code

Results:

If I change the internal return acc + cur to return ACC – cur, it becomes the first element and I start subtracting the elements. Reduce, however, is primarily a specific cumulative traversal



The filter ๐Ÿ‘ป

The filter function, like map, returns a new array. As its name suggests, the filter function mainly filters arrays.

  • A function that tests each element in an array and returnstrueI’m going to keep that element,falseYou don’t keep
  • The parameters are also summapAs with three parameters, the current element is required.
  • If no elements pass, an empty array is returned

Example:

let newarr = arr.filter((item, index, objArr) = >{
    if (typeof item == 'number') return true;
    else return false;
})
console.log(newarr);
Copy the code

Results: [1, 2, 3]



Every ๐Ÿ‘น

The every function also evaluates the elements of an array, but unlike filter, filter retains the filtered elements and returns a new array.

The every function returns a Boolean that tests whether all elements in an array can pass the test of a given function. If one element fails, false is returned. All passes are true

let flag = arr.every((item, index, objArr) = >{
    if(item ! =null) return true;
    else return false;
})
console.log(flag);
Copy the code

Results: true,

Note: If this is an empty array, then no matter what you do, it will return true, okay

let flag = [].every((item, index, objArr) = >{
    return false
})
console.log(flag); // true
Copy the code


Some โ˜  ๏ธ

Some, as opposed to every, tests whether at least one element in the array passes the provided function test. Returns a Boolean value.

Note: If it is an empty array, then no matter what judgment you make, false will be returned, okay

Example:

let arr = [1.2.3.'456'.false, { sex: null }];
let flag = arr.some((item, index, objArr) = >{
    // only {sex: null} is eligible
    if (typeof item == 'object') return true;
    else return false;
})
console.log(flag);  // true
Copy the code