The reduce function can perform operations such as accumulation, filtering, grouping, mapping, etc. as needed, and is a very powerful array method. It is used very frequently in data processing. Many complex logics are very simple if they are processed by reduce. In the actual development work process, some common and super useful code fragments of reduce techniques have been accumulated, and the selection is as follows 10 for your reference
reduce introduction
reduce
It is an array method, which can execute a callback function for each element in the array in turn, and calculate a final value sequentially from left to right. Its syntax is:
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
Among them, callback
is the callback function executed by each element, which contains 4 parameters:
accumulator
: Accumulator, which is the return value of the last callback function execution.currentValue
: The value of the current element.index
: The subscript of the current element.array
: the original array.
initialValue
is optional and represents the initial value of the accumulator.
reduce
The execution of the function is as follows:
1. If not provided initialValue
, the first element of the array will be used as the initial value of the accumulator, otherwise it will be initialValue
used as the initial value of the accumulator.
2. Starting from the second element of the array, execute the callback function for each element in the array in turn.
3. The return value of the callback function is used as the value of the accumulator when the callback function is executed next time.
4. After the callback function is executed for each element in the array, reduce
the function returns the return value of the last callback function, which is the final cumulative value.
Count the number of occurrences of each element in an array
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const count = fruits.reduce((accumulator, currentValue) => {
accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
return accumulator;
}, {
});
console.log(count); // Output: { apple: 3, banana: 2, orange: 1 }
Flatten nested arrays
const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flattenedArray = nestedArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]
group by condition
const people = [
{
name: 'Alice', age: 25 },
{
name: 'Bob', age: 30 },
{
name: 'Charlie', age: 35 },
{
name: 'David', age: 25 },
{
name: 'Emily', age: 30 }
];
const groupedPeople = people.reduce((accumulator, currentValue) => {
const key = currentValue.age;
if (!accumulator[key]) {
accumulator[key] = [];
}
accumulator[key].push(currentValue);
return accumulator;
}, {
});
console.log(groupedPeople);
// Output: {
// 25: [{ name: 'Alice', age: 25 }, { name: 'David', age: 25 }],
// 30: [{ name: 'Bob', age: 30 }, { name: 'Emily', age: 30 }],
// 35: [{ name: 'Charlie', age: 35 }]
// }
Merge multiple arrays into one object
const keys = ['name', 'age', 'gender'];
const values = ['Alice', 25, 'female'];
const person = keys.reduce((accumulator, currentValue, index) => {
accumulator[currentValue] = values[index];
return accumulator;
}, {
});
console.log(person); // Output: { name: 'Alice', age: 25, gender: 'female' }
convert string to object
const str = 'key1=value1&key2=value2&key3=value3';
const obj = str.split('&').reduce((accumulator, currentValue) => {
const [key, value] = currentValue.split('=');
accumulator[key] = value;
return accumulator;
}, {
});
console.log(obj);
// Output: { key1: 'value1', key2: 'value2', key3: 'value3' }
Convert object to query string
const params = {
foo: "bar", baz: 42 };
const queryString = Object.entries(params).reduce((acc, [key, value]) => {
return `${
acc}${
key}=${
value}&`;
}, "?").slice(0, -1);
console.log(queryString); // "?foo=bar&baz=42"
Print the Fibonacci sequence
const fibonacci = n => {
return [...Array(n)].reduce((accumulator, currentValue, index) => {
if (index < 2) {
accumulator.push(index);
} else {
accumulator.push(accumulator[index - 1] + accumulator[index - 2]);
}
return accumulator;
}, []);
};
console.log(fibonacci(10)); // Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Checks if a string is a palindrome
const str = 'racecar';
const isPalindrome = str.split('').reduce((accumulator, currentValue, index, array) => {
return accumulator && currentValue === array[array.length - index - 1];
}, true);
console.log(isPalindrome); // Output: true
Checks for matching parentheses
const str = "(()()())";
const balanced = str.split("").reduce((acc, cur) => {
if (cur === "(") {
acc++;
} else if (cur === ")") {
acc--;
}
return acc;
}, 0) === 0;
console.log(balanced); // true
Get object properties recursively
const user = {
info: {
name: "Jason",
address: {
home: "Shaanxi", company: "Xian" },
},
};
function get(config, path, defaultVal) {
return path.split('.').reduce((config, name) => config[name], config) || defaultVal;
return fallback;
}
get(user, "info.name"); // Jason
get(user, "info.address.home"); // Shaanxi
get(user, "info.address.company"); // Xian
get(user, "info.address.abc", "default"); // default
Handwritten reduce
function myReduce(arr, callback, initialValue) {
let accumulator = initialValue === undefined ? arr[0] : initialValue;
for (let i = initialValue === undefined ? 1 : 0; i < arr.length; i++) {
accumulator = callback(accumulator, arr[i], i, arr);
}
return accumulator;
}
In the above code, myReduce
the function accepts 3 parameters: reduce
the array to be operated on arr
, the callback function callback
and the initial value of the accumulator initialValue
. If no initial value is provided, the first element of the array is used as the initial value of the accumulator.
Next, in the loop, if there is an initialValue, the callback is traversed from the first element. At this time, the second parameter of callabck starts from the first item of the array; if there is no initialValue, it starts from the second element Traversing the callback, the second parameter of the callback is starting from the second item of the array. Starting from the second element of the array, the callback function is executed for each element in the array in turn, and the return value is used as the next callback function The value of the accumulator at execution time.
Finally, myReduce
the function returns the return value of the last callback function, which is the final accumulated value.
This simple reduce
function does not consider many boundary cases and complex application scenarios, but it can help us better understand the reduce
realization principle of the function.