Array内部值的加法,根据特定值。

huangapple go评论65阅读模式
英文:

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) =&gt; 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) =&gt; (i = r.find(e =&gt; e[0] === x &amp;&amp; e[1] === y), i ? i[2] += v : r.push([x,y,v]), r), [])

console.log(result)

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月6日 18:44:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75360271.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定