JavaScript >> Javascript 文檔 >  >> JavaScript

如何在 JavaScript 中使用 reduce() 方法

reduce() 方法將 JavaScript 數組簡化為單個值。它執行給定的 reducer 數組中除空值外的每個元素的函數,產生單個輸出值。

這是它的樣子:

const callback = (accumulator, currentValue, index) => {
    // TODO: do something here
};

const result = array.reduce(callback, initialValue);
  • initialValue — 您要開始的初始值。它用作第一次調用 callback 的第一個參數 .如果跳過,則將數組中的第一個元素用作初始值。
  • accumulator — 上次調用 callback 返回的值 或 initialValue 第一次調用的值。
  • currentValue — 數組中正在處理的當前元素。
  • index — 數組中正在處理的當前元素的索引。如果 initialValue 從索引 0 開始 提供。否則,它從索引 1 開始。

通常,我們使用 reduce() 計算總數的方法,例如數組中的總和、平均值、最小值和最大值。它還可以用於對對像數組中的值進行求和以及展平數組。

對數組的所有值求和

這是一個使用 reduce() 計算數組中所有元素之和的示例 方法:

const array = [1, 9, 7, 4, 3];

const sum = array.reduce((accumulator, current) => {
    return accumulator + current;
});

console.log(`Sum of all numbers is ${sum}`);

// Sum of all numbers is 24

在上面的例子中,為了簡單起見,我使用了箭頭函數。常規函數也可以用作回調。

您還可以傳遞一個初始值將其添加到總數中:

const array = [1, 9, 7, 4, 3];

const sum = array.reduce((accumulator, current) => {
    return accumulator + current;
}, 10);

console.log(`Sum of all numbers is ${sum}`);

// Sum of all numbers is 34

如上所示,我們通過了 10 作為初始值,並添加到總數中。

查找最大值和最小值

reduce() 方法也可以用於查找數組中的最大值和最小值。

下面是一個在數組中查找最大數的示例:

const array = [1, 9, 7, 4, 3];

const max = array.reduce((accumulator, current) => {
    return accumulator > current ? accumulator : current;
});

console.log(`Maximum number is ${max}`);

// Maximum number is 9

同樣,要查找數組中的最小數,您可以執行以下操作:

const array = [1, 9, 7, 4, 3];

const min = array.reduce((accumulator, current) => {
    return accumulator < current ? accumulator : current;
});

console.log(`Minimum number is ${min}`);

// Minimum number is 1

對像數組中的值的總和

reduce() 函數不僅限於對一組數字求和。您還可以總結對像數組中包含的值。但是,您必須提供 initialValue ,讓每個對像都通過你的回調函數:

const array = [
    { value: 5 },
    { value: 1 },
    { value: 2 }
];

const sum = array.reduce((accumulator, current) => {
    return accumulator + current.value;
}, 0);

console.log(`Sum of all object values is ${sum}`);

// Sum of all object values is 8

計算數組中值的實例

可以使用 reduce() 的另一種情況 方法是計算一個數組中不同值出現的次數。

假設您有以下名稱數組:

const names = ['John', 'Alice', 'Maria', 'Mir', 'John'];

現在,我們想知道每個名字在數組中出現了多少次。

由於我們想將數組歸約為一個對象,我們必須傳遞一個空對像作為 initialValue

const counts = names.reduce((accumulator, name) => {
    // TODO: do something here
}, {});

在第一次迭代中,accumulator 將是 {}name 將是 John .我們可以簡單地添加 nameaccumulator 並將計數設置為 1:

const counts = names.reduce((accumulator, name) => {
    return accumulator[name] = 1;
}, {});

在接下來的迭代中,我們將首先檢查 name accumulator 中已存在屬性 或不。如果是這樣,我們只會將計數加 1:

const counts = names.reduce((accumulator, name) => {
    if (name in accumulator) {
        accumulator[name] = accumulator[name] + 1;
    } else {
        accumulator[name] = 1;
    }
    return accumulator;
}, {});

而已。一旦該過程完成,counts 變量應包含以下對象:

{
  "John": 2,
  "Alice": 1,
  "Maria": 1,
  "Mir": 1
}

扁平化數組

reduce() 方法也可用於展平多維數組:

const flowers = [['🍀'], ['🌷'], ['🌹'], ['🌻', '🌺']];

const flattened = flowers.reduce((accumulator, item) => {
    return accumulator.concat(item);
}, []);

console.log(flattened);

// [ '🍀', '🌷', '🌹', '🌻', '🌺' ]

Tutorial JavaScript 教程
  1. 你吊嗎

  2. 等等,React 不是關於虛擬 DOM 的嗎?

  3. 我的第一個平台遊戲——鮑勃歷險記

  4. 通過貢獻學習

  5. 我可以合併! (實際上是 git 為我做的)

  6. 關於我的第一次 jQuery 體驗的思考

  7. React 自定義鉤子:一個簡單的解釋🐱‍👤

  1. 如何使用 Ionic 框架組件和手勢 API 在 ReactJS 中創建底部抽屜

  2. 聊天消息如何存儲在 Firestore 中?

  3. 為 VSCode Webviews 偽造 React

  4. 從頭開始創建 Netflix 克隆:JavaScript PHP + MySQL 第 20 天

  5. 從類組件遷移到 React 鉤子

  6. 如何使用 Redux 管理狀態

  7. JavaScript Map、Filter 和 Reduce 方法簡介

  1. 如何在 Vue.js 中安全地實現 OAuth

  2. 原子 CSS-in-JS

  3. 2020 年前端開發人員需要的概念

  4. 項目 91 of 100 - 使用 <FlatList /> 在 React Native 中構建雜貨清單