簡體   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