繁体   English   中英

如何找到对象中所有值的总和以及数组中包含的对象的总和?

[英]How find sum of all values in object and included objects in array?

如何找到该对象中所有值的总和? 在包含对象的数组中,另一个对象具有值,并且可以是具有相似结构对象的“下一个”数组。

{
  value: 4,
  next: [
    {
      value: 3,
      next: [...]
    },
    {
      value: 3,
      next: [...]
    },
    ...
  ]
}

您将需要递归来处理对象的任意嵌套:

 const nestedSum = o => (o.next || []).reduce((acc, o) => acc + nestedSum(o), o.value); // Demo const data = { value: 4, next: [{ value: 3, next: [{value: 5}] }, { value: 3, next: [] }, ] }; console.log(nestedSum(data)); 

使用reduceObject.entries递归求和:

 const obj = { value: 4, next: [{ value: 3, next: [{ value: 1 }] }, { value: 3, next: [{ value: 2, next: [] }] }] }; const sum = (obj) => Object.entries(obj).reduce((acc, [k, v]) => acc + ( k === 'next' ? v.map(sum).reduce((s, x) => s + x, 0) : k === 'value' ? v : 0) , 0); console.log(sum(obj)); 

 function sum(obj, current = 0) { const nextSum = (obj.next || []).reduce((nextSum, obj) => nextSum + sum(obj, current), 0) return current + nextSum + obj.value } const example = { value: 4, next: [ { value: 3, next: [{ value: 7 }] }, { value: 3 } ] } console.log(sum(example)) // must be 17 

您需要一个递归函数,并检查键的值是否为数字,然后添加变量;否则,如果它是一个类似于next的数组,则对其进行迭代,然后再次使用新对象调用同一函数

 let data = { value: 4, next: [{ value: 3, next: [{ value: 4 }, { value: 5 }] }, { value: 3, next: [{ value: 2 }] } ] } let sum = 0; function findSum(obj) { for (let keys in obj) { if (typeof obj[keys] === 'number') { sum += obj[keys]; } else if (Array.isArray(obj[keys]) && obj[keys].length > 0) { obj[keys].forEach(function(item) { findSum(item) }) } } } findSum(data); console.log(sum) 

对象的结构称为Tree Tree(数据结构) 您可以使用广度优先深度优先的方法遍历树并沿途收集和。

其他答案表示您必须递归进行,但是可以使用广度优先的方法来迭代地进行,我在代码片段中向您展示了这两种方法。

我扩展了您的数据样本,添加了可能没有下一个值的空值(您可以使用任何类型的检查)。

 let data = { value: 4, next: [ { value: 3, next: [ { value: 5, next: null }, { value: 6, next: null } ] }, { value: 2, next: [ { value: 2, next: null }, { value: 3, next: [ { value: 7, next: null }, { value: 8, next: null } ] } ] } ] } // iterative approach function breadthFirst(node){ let sum = 0 let q = [node] while(q.length > 0){ let node = q.pop() sum += node.value if (node.next !== null) { for (let other of node.next){ q.push(other) } } } return sum } console.log('breadthFirst sum (iterative):', breadthFirst(data)) // recursive apporach function depthFirst(node){ let sum = 0 function recursion(node){ sum += node.value if (node.next !== null) { for (let other of node.next){ recursion(other) } } } recursion(node) return sum } console.log('depthFirst sum (recursive):', depthFirst(data)) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM