返回

巧用JavaScript统计数组中相同的数量:简便有效的方法

前端

在JavaScript中,我们经常需要对数组中对象的属性进行统计。例如,我们可能有一个包含产品名称和数量的数组,我们需要统计每个产品名称出现的次数,并将其数量相加。在本文中,我们将介绍如何使用JavaScript高效地完成此操作。

1. 使用循环统计数组中相同的数量

最简单的方法是使用循环来统计数组中相同的数量。我们可以使用for循环或forEach循环来遍历数组,并在每次迭代中检查当前元素是否与我们想要统计的元素相等。如果相等,则我们将该元素的数量增加1。

// 使用for循环统计数组中相同的数量
const products = [
  { name: 'iPhone', quantity: 2 },
  { name: 'iPad', quantity: 1 },
  { name: 'MacBook', quantity: 3 },
  { name: 'iPhone', quantity: 4 },
  { name: 'iPad', quantity: 2 },
];

const productName = 'iPhone';
let quantity = 0;

for (let i = 0; i < products.length; i++) {
  if (products[i].name === productName) {
    quantity += products[i].quantity;
  }
}

console.log(`Total quantity of ${productName}: ${quantity}`); // Output: Total quantity of iPhone: 6

2. 使用数组方法统计数组中相同的数量

JavaScript还提供了一些数组方法,可以帮助我们更轻松地统计数组中相同的数量。例如,我们可以使用reduce()方法来将数组中的元素累加起来,并使用filter()方法来筛选出满足特定条件的元素。

// 使用reduce()方法统计数组中相同的数量
const products = [
  { name: 'iPhone', quantity: 2 },
  { name: 'iPad', quantity: 1 },
  { name: 'MacBook', quantity: 3 },
  { name: 'iPhone', quantity: 4 },
  { name: 'iPad', quantity: 2 },
];

const productName = 'iPhone';
const totalQuantity = products.reduce((acc, product) => {
  if (product.name === productName) {
    return acc + product.quantity;
  }
  return acc;
}, 0);

console.log(`Total quantity of ${productName}: ${totalQuantity}`); // Output: Total quantity of iPhone: 6
// 使用filter()方法统计数组中相同的数量
const products = [
  { name: 'iPhone', quantity: 2 },
  { name: 'iPad', quantity: 1 },
  { name: 'MacBook', quantity: 3 },
  { name: 'iPhone', quantity: 4 },
  { name: 'iPad', quantity: 2 },
];

const productName = 'iPhone';
const sameProducts = products.filter(product => product.name === productName);
const totalQuantity = sameProducts.reduce((acc, product) => acc + product.quantity, 0);

console.log(`Total quantity of ${productName}: ${totalQuantity}`); // Output: Total quantity of iPhone: 6

3. 使用Lodash统计数组中相同的数量

如果您正在使用Lodash库,还可以使用它的countBy()函数来统计数组中相同的数量。该函数接收一个数组和一个函数作为参数,函数用于提取每个元素的属性值,然后返回一个对象,其中键是属性值,值是该属性值出现的次数。

// 使用Lodash统计数组中相同的数量
const _ = require('lodash');

const products = [
  { name: 'iPhone', quantity: 2 },
  { name: 'iPad', quantity: 1 },
  { name: 'MacBook', quantity: 3 },
  { name: 'iPhone', quantity: 4 },
  { name: 'iPad', quantity: 2 },
];

const productName = 'iPhone';
const count = _.countBy(products, product => product.name);
const totalQuantity = count[productName];

console.log(`Total quantity of ${productName}: ${totalQuantity}`); // Output: Total quantity of iPhone: 6

无论您选择哪种方法,都可以轻松地统计JavaScript数组中相同数量的元素。这些方法简单易用,可以帮助您快速解决问题。