Some applications of reduce method of js array

A method in js reduce()that can be used to aggregate array elements into a single value takes a callback function as an argument and calls that function on each array element in order to accumulate it into an accumulator variable. Here are some practical applications:

  1. Array summation: Calculate the sum of an array by adding the elements of the array using the reduce() method.

    const numbers = [1, 2, 3, 4, 5];
    const sum = numbers.reduce(
      (accumulator, currentValue) => accumulator + currentValue
    );
    console.log(sum); // 15
    
  2. Array average: Use the reduce() method to add the elements of the array and divide by the length of the array to calculate the average of the array.

    const numbers = [1, 2, 3, 4, 5];
    const sum = numbers.reduce(
      (accumulator, currentValue) => accumulator + currentValue
    );
    const average = sum / numbers.length;
    console.log(average); // 3
    
  3. Array maximum/minimum value: Use the reduce() method to compare the array elements with the current maximum/minimum value to calculate the maximum/minimum value of the array.

    const numbers = [1, 2, 3, 4, 5];
    const max = numbers.reduce((accumulator, currentValue) =>
      Math.max(accumulator, currentValue)
    );
    console.log(max); // 5
    
    const min = numbers.reduce((accumulator, currentValue) =>
      Math.min(accumulator, currentValue)
    );
    console.log(min); // 1
    
  4. Array deduplication: use the reduce() method to traverse the array and add each element to a new array, but only if the element does not exist in the new array.

    const numbers = [1, 2, 3, 2, 1, 4, 5];
    const uniqueNumbers = numbers.reduce((accumulator, currentValue) => {
      if (!accumulator.includes(currentValue)) {
        accumulator.push(currentValue);
      }
      return accumulator;
    }, []);
    console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
    
  5. Object attribute sum/average: Use the reduce() method to add the attribute values ​​in the object array and divide by the length of the object array to calculate the average value of the attribute.

    const data = [
      { name: "Alice", score: 80 },
      { name: "Bob", score: 75 },
      { name: "Charlie", score: 90 },
    ];
    const sum = data.reduce(
      (accumulator, currentValue) => accumulator + currentValue.score,
      0
    );
    const average = sum / data.length;
    console.log(average); // 81.67
    

    These are just some common applications of the reduce() method, it can also be used for more complex operations such as calculating the standard deviation or variance of an array, etc.

  6. Implement object arrays to classify according to an object property

    You can use JavaScript's reduce method to sort by a property in an array of objects. Here is the sample code:

    const data = [
      { name: "Alice", age: 20, gender: "female" },
      { name: "Bob", age: 30, gender: "male" },
      { name: "Charlie", age: 25, gender: "male" },
      { name: "David", age: 22, gender: "male" },
      { name: "Eva", age: 18, gender: "female" },
      { name: "Frank", age: 40, gender: "male" },
    ];
    
    const groupedData = data.reduce((acc, obj) => {
      const key = obj.gender;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(obj);
      return acc;
    }, {});
    
    console.log(groupedData);
    

    The above code will sort based on the property in the object array genderand save the sorted data in a new object. Among them, reducethe initial value of the method is an empty object {}, and each iteration will genderadd the object to the classified array according to the properties of the current object. Ultimately, groupedDatathe variable will contain the following:

    {
      "female": [
        { "name": "Alice", "age": 20, "gender": "female" },
        { "name": "Eva", "age": 18, "gender": "female" },
      ],
      "male": [
        { "name": "Bob", "age": 30, "gender": "male" },
        { "name": "Charlie", "age": 25, "gender": "male" },
        { "name": "David", "age": 22, "gender": "male" },
        { "name": "Frank", "age": 40, "gender": "male" },
      ]
    }
    

    The above code can be modified according to your needs to classify based on different attributes.

Guess you like

Origin blog.csdn.net/lwf3115841/article/details/131861995