英文:
Addition of values inside an Array according to certain value
问题
我有一个类似这样的数组:
let array = [[0, 1, 4.75], [0, 1, 2.12], [0, 3, 8.1]];
期望的输出是:
let expectedOutput = [[0, 1, 6.87], [0, 3, 8.1]];
在这种情况下,4.75 + 2.12
已经被相加,因为前两个值匹配 [0, 1]
。
我想查找子数组中的第一个和第二个值,并将具有相同第一个和第二个值的所有子数组的第三个值相加。你能帮助我吗?
英文:
I have an array like this:
let array = [[0, 1, 4.75], [0, 1, 2.12], [0, 3, 8.1]];
Expected output:
let expectedOutput = [[0, 1, 6.87], [0, 3, 8.1]];
In this case 4.75 + 2.12
has been summed up because first two values were matching [0, 1]
.
I want to lookup the first and second value in the sub-array und sum the third value of all the sub-arrays that has the same first and second value. Can you please help me out?
答案1
得分: 1
const array = [
[0, 1, 4.75],
[0, 1, 2.12],
[0, 3, 8.1]
];
// 根据第一和第二项对数组进行分组
const groups = {}
for (const [a1, a2, a3] of array) {
if (!(a1 in groups)) {
groups[a1] = {}
}
if (!(a2 in groups[a1])) {
groups[a1][a2] = []
}
groups[a1][a2].push(a3)
}
// 计算第三项的总和
const result = []
for (const a1 in groups) {
for (const a2 in groups[a1]) {
const sum = groups[a1][a2].reduce((s, c) => s + c, 0)
result.push([+a1, +a2, sum])
}
}
console.log(result)
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const array = [
[0, 1, 4.75],
[0, 1, 2.12],
[0, 3, 8.1]
];
// groups arrays by first and second item
const groups = {}
for (const [a1, a2, a3] of array) {
if (!(a1 in groups)) {
groups[a1] = {}
}
if (!(a2 in groups[a1])) {
groups[a1][a2] = []
}
groups[a1][a2].push(a3)
}
// sum the third item
const result = []
for (const a1 in groups) {
for (const a2 in groups[a1]) {
const sum = groups[a1][a2].reduce((s, c) => s + c, 0)
result.push([+a1, +a2, sum])
}
}
console.log(result)
<!-- end snippet -->
答案2
得分: 0
构建结果时,请检查当前元素是否与先前的元素匹配,然后要么仅添加该值,要么添加整个元素:
let array = [[0, 1, 4.75], [0, 1, 2.12], [0, 3, 8.1]];
const result = array.reduce((r, [x, y, v], i) => {
i = r.find(e => e[0] === x && e[1] === y);
if (i) {
i[2] += v;
} else {
r.push([x, y, v]);
}
return r;
}, []);
console.log(result);
英文:
When building the result, check if the current element matches a previous one, and then either add only the value or the whole element:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let array = [[0, 1, 4.75], [0, 1, 2.12], [0, 3, 8.1]];
const result = array.reduce( (r, [x,y,v], i) => (i = r.find(e => e[0] === x && e[1] === y), i ? i[2] += v : r.push([x,y,v]), r), [])
console.log(result)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论