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. It can do a lot of functions, through the callback function. Reduce parameter

  • The first argument is a callback function that takes four arguments (accumulator, current value, current index, and original array). The last two are optional.
function(acc,current,index,arr) = >{
    return acc+cur;
}
Copy the code
  • Second argument: is the initial value of the accumulator for the first argument of the callback function

Note: if no initial value is given, then the initial value is the first element of the original array, and the calculation starts with the second element. Given an initial value, you start with the first element.

Usage scenarios

accumulator

  • Sums the values of stored values
Let the result = [1, 2, 3, 4] reduce ((acc, cur) = > {return acc + cur; //acc is the accumulator (the initial value is the first element of the array), cur is the current element}) console.log(result); // There is no initial value, so we start from the second element of the array, so we process the above array. The callback runs the copy code 3 timesCopy the code
  • The sum is given to the initial value
Let the result = [1, 2, 3, 4] reduce (acc, cur, index, o = > {return acc + cur; },10) console.log(result); // The first element of the array is evaluated because there is an initial value, so the above array is processed. The callback is run 4 timesCopy the code

Find the largest element in the array

Const Max = function (list) {return list.reduce(function (x, y) {return x > y? x : y }); }Copy the code

Array to heavy

Problem description: Array deduplication, as the name implies, is to remove the duplicate values in the array, so that multiple identical values into one, and finally make the array does not contain duplicate values.

Example: one array:,2,3,4,4,5,5,5,6,7 [1], the array to heavy becomes,2,3,4,5,6,7 [1].

reduce+includes/ resuce+indexOf

var unique = function (list) {
    return list.reduce((acc, current) => {
        if (!acc.includes(current)) {
            acc.push(current);
        }
        return acc;
    }, []);
};
Copy the code

filter+indexOf

var unique = function (list) {
    return list.filter((current, index, arr)=>{
        return arr.indexOf(current) === index;
    });
};
Copy the code

Extended operators… +Set

var unique = function (list) {
    var set = new Set(list);
    return [...set];
};
Copy the code

{}+Object.keys()

var unique = function (list) {
    var map = {};
    list.forEach((value, index)=>{
        if(!map[value]) {
            map[value] = true;
        }
    });
    return Object.keys(map);
};
Copy the code

There are implementations similar to this

  • New array + include
  • New array + indexOf
  • Map + […map.keys()]

Objects are classified by attributes

const bills=[{type:'transfer',momey:233}, {type:'study',momey:341}, {type:'shop',momey:821}, {type:'transfer',money:821}, {type:'study',momey:821} ] let result=bills.reduce((acc,cur)=>{ if(! Acc [cur.type]){// Create an empty array to hold acc[cur.type]=[]; } acc[cur.type]. Push (cur) return acc; },[])// Set the initial value of the accumulator to an empty array, as a container for sorting console.log(result); // Output [transfer: [{type: 'transfer', momey: 233},{type: 'transfer', money: 821}], study: [{type: 'study', momey: 341 }, { type: 'study', momey: 821 } ], shop: [ { type: 'shop', momey: 821 } ] ]Copy the code

Use native JavaScript to implement a method that determines which tags occur the most in your HTML and counts that number.

Steps:

  1. Get all tags:document.querySelector(*): Gets the NodeList array with all the tags.
  2. Convert NodeList to list […NodeList];
  3. Use Reduce to convert the nodelist into an object with the label name and the attribute name and the number of tags as the attribute value.
  4. Enumerate elements into arrays with Object.entries()

For example: Object. Entires ({2, a: 1, b: c: 3}) will get [[‘ a ‘, 1], [‘ b ‘, 2], [‘ c ‘, 3]] 5. Return the maximum value of the array using reduce

Onload =function(){function getFrequentTag(){// get nodeList const tagMap=[...document.querySelectorAll('*')].map(x=>x.tagName).reduce((acc,tag)=>{ acc[tag]=acc[tag]? acc[tag]+1:1; // If the element is present in the array, the value is +1, otherwise the element is created, and the value is set to 1. // Get the attribute name with the tag name, Keys (tagMap).reduce((acc, current) => {return tagMap[acc] > tagMap[current]? acc : current; }); } console.log(getFrequentTag()); }Copy the code

The upgraded version gets the x – time tag

var maxCount = function (list, x) { const map=[...document.querySelectorAll('*')].map(x=>x.tagName).reduce((acc,tag)=>{ acc[tag]=acc[tag]? acc[tag]+1:1; ]  return acc; ] }, {}); var list = Object.keys(map).sort((a, b)=>{ return map[b]-map[a] }) return x<0? list[list.length+x]: list[x]; };Copy the code