10 Super Practical Reduce Tips

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

Introduction to reduce

reduce 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.

The execution process of the reduce function is as follows:

  1. If no initialValue is provided, the first element of the array is used as the initial value of the accumulator, otherwise initialValue is used as the initial value of the accumulator.

  2. Executes the callback function for each element in the array in turn, starting from the second element of the array.

  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 executing the callback function for each element in the array, the reduce 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 the 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 array

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 & amp;key2=value2 & amp;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 & amp;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]

Check if the string is a palindrome

const str = 'racecar';
const isPalindrome = str.split('').reduce((accumulator, currentValue, index, array) => {
  return accumulator & amp; & amp; currentValue === array[array. length - index - 1];
}, true);
console.log(isPalindrome); // Output: true

Check if brackets match

const str = "(()()())";
const balanced = str.split("").reduce((acc, cur) => {
  if (cur === "(") {
    acc ++ ;
  } else if (cur === ")") {
    acc--;
  }
  return acc;
}, 0) === 0;
console.log(balanced); // true

Recursively get object properties

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"); // Shanxi
get(user, "info.address.company"); // Xian
get(user, "info.address.abc", "default"); // default

Handwritten reduce

You can better understand how it works by writing a simple reduce function by hand:

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, the myReduce function accepts 3 parameters: the array arr to perform the reduce operation, and the callback function callback and the accumulator’s initial value 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, the myReduce 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 implementation principle of the reduce function.

About this article

Author: shichuan

https://juejin.cn/post/7224043114360225847

Last

Welcome to [Front-end Bottle Jun]ヽ(°▽°)ノ?

Reply to “communication”, blow water, chat about technology, and complain!

Reply to “reading” and read high-quality articles every day!

If this article is helpful to you, “Looking at” is the biggest support!


Don't forget to like it at the end!