在3D数组中求和1种类型

时间:2019-10-17 15:14:17

标签: javascript

我不知道如何只对3D阵列的一部分求和。

让我们说这是我的数组,我怎么只能将类型价格的总和求和?

0: {Type: "Food", Price: "100"}
1: {Type: "Entertainment",  Price: "200"}

我希望能够对数组的一部分求和,总共得到300。

2 个答案:

答案 0 :(得分:0)

3D阵列是什么意思?如果您的数组形状为[{Type: "Food", Price: "100"}, {Type: "Entertainment", Price: "200"}],则可以执行以下操作:

const arr = [{Type: "Food", Price: "100"}, {Type: "Entertainment", Price: "200"}];

const sum = arr.map(item => item.Price).reduce((sum, value) => sum + +value, 0);

console.log(sum)

答案 1 :(得分:0)

considering following array, you can achieve 300 sum by this code

const array = [
    { Type: "Food", Price: "100" },
    { Type: "Entertainment", Price: "200" }
];

const sumOfPrices = array.reduce((sum, element) => (sum + +element.Price), 0);

console.log(sumOfPrices);