A picture to understand es6 commonly used data iteration functions map, filter, fill, reduce

1. A picture is worth a thousand words

In front-end development, js array processing is the most commonly used. Except for loop, with the popularity of es6, attributes like reduce(), filter(), map(), some(), every() and... are the most common. commonly used.
I saw this picture from the Internet by chance today, it is really eye-catching, it is really clear at a glance, and people can understand the purpose of related functions without a single explanation

insert image description here

2. Description of key functions

1. map and forEach

The function of map is similar to that of forEach, but map has a return value and generates a new array without changing the original array, forEach has no return value

  • map: Let the array generate a new array through calculation
  • forEach: Let each item of the array perform an operation
const a = [1, 2, 3];
const b = a.map(x => x * 2);
let c=a.forEach(x=>x*2)
console.log(a,b,c);

Output: > Array [1, 2, 3] Array [2, 4, 6] undefined

2, filter (filter)

Returns a new array that satisfies the condition without affecting the original array

  • Return value: Array
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log('原值',words);
console.log('结果',result);
-------------------------------
输出:
> "原值" Array ["spray", "limit", "elite", "exuberant", "destruction", "present"]
> "结果" Array ["exuberant", "destruction", "present"]

3, some (arbitrary), every (all)

  • Return value: Boolean
  • every: judge whether each element satisfies the condition, if so, return true, otherwise false
  • some: judge whether any one of each element satisfies the condition, if so, return true, otherwise false
console.log([1, undefined, 1].some((x) => x !== 1)); // true
console.log([1, 30, 39, 29, 10, 13].every(x=>x<40)); // true

4. reduce (cumulative)

The reduce() method sequentially executes the user-provided "reducer" callback function on each element of the array, and passes in the return value of the calculation on the previous element, which is finally calculated as a value

grammar

arr.reduce(callback,[initialValue])

  • callbackThe function to execute for each element in the array. Its return value becomes the value of the parameter the next time it is called. For the last call, the return value becomes the final return value
  • initialValue(可选参数)When the initialValue parameter is set, the initial value of the first parameter of callback will default to initialValue.
const array = [15, 16, 17, 18, 19];

function reducer(accumulator, currentValue, index) {
    
    
  const returns = accumulator + currentValue;
  console.log(
    `accumulator: ${
      
      accumulator}, currentValue: ${
      
      currentValue}, index: ${
      
      index}, returns: ${
      
      returns}`,
  );
  return returns;
}

array.reduce(reducer);

insert image description here

The role of default values

If the component is empty, if the default value is not set, an error will be reported when calling reduce, but after the default value is set, it can be executed normally

var  arr = [];
var sum = arr.reduce(function(prev, cur, index, arr) {
    
    
    console.log(prev, cur, index);
    return prev + cur;
})
console.log(arr,sum) // Error: Reduce of empty array with no initial value
var sumDefault = arr.reduce(function(prev, cur, index, arr) {
    
    
    console.log(prev, cur, index);
    return prev + cur;
},0)
console.log(arr,sumDefault) // Array[] 0

common application

1. Group summation, multiplication, comparison, etc.

const  arr = [1, 2, 3, 4];
const sum = arr.reduce((x,y)=>x+y)
const mul = arr.reduce((x,y)=>x*y)
var max = arr.reduce(function (prev, cur) {
    
    
    return Math.max(prev,cur);
});
console.log( sum ); //求和,10
console.log( mul ); //求乘积,24
console.log( max ); //max=4

2. Array deduplication, filtering, and joint functions such as filter and map

let  arr = [1, 2, 3, 4, 5, 4, 3, 2, 1];
let newArr = arr.reduce(function (prev, cur) {
    
    
    cur>3 && prev.push(cur*2);
    return prev;
},[]);
console.log(newArr) // [8, 10, 8]

3. Function composition

const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = s => s.toUpperCase()

// 函数组合
function compose(...funs) {
    
    
    if (funs.length === 0) {
    
    
        return arg => arg;
    }
    if (funs.length === 1) {
    
    
       return funs[0];
    }
    return funs.reduce((a, b) => (...arg) => a(b(...arg)))

}
var arr = ['one', 'two', 'three'];
// 执行组合函数
let fu=compose(toUpper, first, reverse)
console.log(fu(arr))

Guess you like

Origin blog.csdn.net/lqh4188/article/details/128145435