As front-end people, we often get some kind of list of data in the form of an array and need to convert it to something else. One very powerful method built into all arrays in JavaScript is to use the reduce function. It was first introduced in ECMAScript 5.1 and was customized in ECMAScript® 2022 in April. Below I’ll cover the basic syntax and share my practices in using reduce functions:

  1. Computes the sum/maximum of all values in the array
  2. Array to heavy
  3. Convert a two-dimensional array to a one-dimensional array
  4. Count the number of occurrences of each element in the array
  5. Filtering and mapping large data sets for better performance practices

grammar

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
Copy the code

The Reducer function receives 4 parameters :Accumulator (ACC), Current Value (CUR) (Current element Value), Current Index (IDX) (Current Index), Source Array (SRC) (Source array, that is, the object being traversed).

Accumulator and currentValue are two different values when the callback function is first executed: If initialValue is provided when reduce() is called, accumulator is initialValue and currentValue is the first value in the array. If no initialValue is provided, accumulator takes the first value in the array and currentValue takes the second value in the array.

Here are some things to note:

If the array is empty and no initialValue is provided, TypeError is raised. If the array has only one element (regardless of position) and no initialValue is provided, or if initialValue is provided but the array is empty, then the unique value will be returned and the callback will not be executed

Reduce does not change the object it calls directly, but the object can be changed by calling CallbackFN.

If you are interested in further research, more information can be found hereOfficial specification document

Its compatibility in major browsers is shown in figure ~

Maybe the above introduction is boring, next we will share the practice!

Calculate the sum, or maximum, of all the values in the array

// process the summation accumulator
const delTotal = (acc, item) = > {
  return acc + item;
};

// Process the maximum accumulator
const delMax = (acc, item) = > {
  return (acc > item) ? acc : item
};

const data = [1.2.3];
const total = data.reduce(delTotal);
const max = data.reduce(delMax);

console.log("The sum is: ", total); //The sum is: 6
console.log("The max is: ", max); //The max is: 3
console.log("data: ", data); //data: [1, 2, 3]
Copy the code

The same is true for arrays of objects. Note that if you are dealing with arrays of objects, the values contained in the array must provide initial values in order for each item to pass through your function properly

Array deduplication

const numberArray = [1.3.4.5.4.5.3.4]
const stringArray = ['a'.'b'.'a'.'b'.'c'.'e'.'e']

const delRepetition = (accumulator, currentValue) = > {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue)
  }
  return accumulator
}

const repNumberArray = numberArray.reduce(delRepetition,[])
const repStringArray = stringArray.reduce(delRepetition,[])

console.log("The repNumberArray is: ", repNumberArray); //The repNumberArray is: [1, 3, 4, 5]
console.log("The repStringArray is: ", repStringArray); //The repStringArray is: ["a", "b", "c", "e"]

Copy the code

There are many ways to de-duplicate an array, and this may not be optimal, but it’s an idea. If you are using an environment that is compatible with Set and array.from (), you can use let orderedArray = array. from(new Set(myArray)); To get a deduplicated array ~

Convert a two-dimensional array to a one-dimensional array

const flattened = [[0.1], [2.3], [4.5]].reduce(
 ( acc, cur ) = > acc.concat(cur),
 []
);

console.log("flattened: ", flattened); //flattened: [0, 1, 2, 3, 4, 5]

Copy the code

Side challenge: How do I convert a multidimensional array to a one-dimensional array using array.reduce()? Write down your solution in the comments below

Count the number of occurrences of each element in the array

The number of occurrences of statistics is also a common scenario, such as voting statistics. The following simulation uses voting statistics in a front-end framework



const initialValue = {};

const reducer = (tally, vote) = > {
  if(! tally[vote]) { tally[vote] =1;
  } else {
    tally[vote] = tally[vote] + 1;
  }
  return tally;
};

const votes = [
  "vue"."react"."angular"."vue"."react"."angular"."vue"."react"."vue"
];
const result = votes.reduce(reducer, initialValue);

console.log("Result: ", result)  // Result: {vue: 4, react: 3, angular: 2}
console.log("Vue: ", result.vue) // Vue: 4
console.log("React: ", result.react) // React: 3
Copy the code

Similarly, you can handle categorizing objects by attribute

Filter and map large data sets for better performance

We all know how to filter arrays. JavaScript provides a filter() method to filter array objects. Let’s take an example of a large data array (1 million data) and filter all even numbers to compare performance

const bigData = [];
for (var i = 0; i < 1000000; i++) {
  bigData[i] = i;
}

const filterBegin = Date.now()
var filterMappedBigData = bigData.filter((value) = > {
  return value % 2= = =0;
})

const filterEnd = Date.now()
const filtertimeSpent = (filterEnd-filterBegin)/1000 + "s";


const reducedBegin=Date.now();
var reducedBigData = bigData.reduce((acc, value) = > {
  if (value % 2= = =0) {
    acc.push(value);
  }
  returnacc; } []);const reducedEnd = Date.now();
const reducedtimeSpent = (reducedEnd-reducedBegin)/1000 + " s";


console.log("filtered Big Data:", filtertimeSpent)
console.log("reduced Big Data:", reducedtimeSpent)
Copy the code

In the console, we can see that the filter() takes 25 milliseconds and the reduced() takes 20 milliseconds. The reduced() may take less time if you test the reduced() in a local environment. Of course, interested students, You can also experiment with map() and find that reduced() takes less time to process big data!

filtered Big Data: 0.025 s
reduced Big Data: 0.020 s
Copy the code

This is especially true if you are working separately on the filtered data. If we are dealing with a lot of data information, it is helpful to know that the Reduce () function can combine all these operations together to greatly improve performance

The last

This article shares some of the techniques I use in reduce() from syntax to practice. I hope it will be useful to introduce some of the techniques. Of course, there are many scenarios that can be combined with it, such as writing functions, checking nested objects and so on