gpt4 book ai didi

javascript - 在 JavaScript 数组中求和

转载 作者:行者123 更新时间:2023-12-02 17:47:47 25 4
gpt4 key购买 nike

我有一个正在我的页面上创建的动态 JavaScript 数组(这些数字都不会相同,有很多变化),例如:

 myArray[ 1 ] = [295518, 2];
myArray[ 2 ] = [123518, 123];
myArray[ 3 ] = [295518, 43];
myArray[ 4 ] = [295518, 65];
myArray[ 5 ] = [234518, 3];
myArray[ 6 ] = [567518, 56];

该数组的解释:

                [id number, quantity]
myArray[ 1 ] = [295518, 2];

我需要将所有类似的 id 数组元素分组在一起并对它们的值求和。

 For instance: 295518 would add 2 + 43 + 65 = 110

然后我需要它用值更新页面上的 id:

 $("#295518").text(110); 

所以我的想法是这样的,但我不知道如何用 JavaScript 编写它:

 [start JavaScript loop]
[grab distinct ids]
[start id loop]
[grab all values based on id]
[sum their qty values]
[set the id element on the page with the sum value]
[example: $("#295518").text(110); ]
[end id loop]
[/end JavaScript loop]

最佳答案

这应该可以解决问题:

var myArray = [
[295518, 2],
[123518, 123],
[295518, 43],
[295518, 65],
[234518, 3],
[567518, 56]
]

var result = {};

for (var i in myArray) {
var key = myArray[i][0];
var value = myArray[i][1];
if (result[key]) {
result[key] += value;
} else {
result[key] = value;
}
}

console.log(result);

这与 jQuery 是一样的:

var myArray = [];
myArray.push([295518, 2]);
myArray.push([123518, 123]);
myArray.push([295518, 43]);
myArray.push([295518, 65]);
myArray.push([234518, 3]);
myArray.push([567518, 56]);

var result = {};

$(myArray).each(function() {
var key = this[0];
var value = this[1];
if (result[key]) {
result[key] += value;
} else {
result[key] = value;
}
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<强> Here's a working example...

关于javascript - 在 JavaScript 数组中求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21608338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com