aryakeio
aryakeio

Reputation: 11

Find the sum of values inside a nested array

I have a nested array that looks like this:

let scores = [  
[[2, 1, 0], [2, 1, 0]],  
[[4, 2, 0]],  
[[4, 2, 0]],  
[[4, 2, 0],[2, 1, 0]]  
]  

What I'm trying to do is get the highest value of each array (and sum the highest values in arrays that contain more than one array, ie. inside the first array, [[2,1,0],[2,1,0]], I need to sum the highest values of each array which in this case is 2+2.) My thought is to shift() the first value of each array OR slice()/remove the lower values so my array looks like this:
newScores = [[[2],[2]], [4], [4], [[4],[2]]]

Ultimately, my desired output is: output = [[4], [4], [4], [6]]

Hope someone can provide some direction! Thanks!

Upvotes: 0

Views: 1506

Answers (4)

M.Dhee
M.Dhee

Reputation: 63

let scores = [  
[[2, 1, 0], [2, 1, 0]],  
[[4, 2, 0]],  
[[4, 2, 0]],  
[[4, 2, 0],[2, 1, 0]]  
]

function nestedArray(arr){
   let result=[];
   let counter = 0;
   for(let i=0;i<arr.length;i++){
       if(arr[i].length>1){
           var a = [Math.max(...arr[i][counter])];
           var b = [Math.max(...arr[i][counter+1])];
        result.push(a.map((ax,bx)=>ax+b[bx]));
       }
       if(arr[i].length===1){
            result.push([Math.max(...arr[i][counter])]);

       }


   }
   return result;

}
nestedArray(scores);

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122145

You can do this with map(), reduce() and Math.max methods and spread syntax ....

let scores = [  
  [[2, 1, 0], [2, 1, 0]],  
  [[4, 2, 0]],  
  [[4, 2, 0]],  
  [[4, 2, 0],[2, 1, 0]]  
]  

const result = scores.map(a => a.reduce((r, e) => {
  return +r + Math.max(...e)
}, []))

console.log(result)

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138557

 const result = scores.map(groups =>
     groups.map((sum, group) => sum + Math.max(...group), 0)
 );

Upvotes: 1

gavgrif
gavgrif

Reputation: 15519

You need to iterate of the parent array, then for each array in that - iterate over its arrays, getting the max number from each array - then summing the children arrays and finally pushing the totals into the output array.

let scores = [  
[[2, 1, 0], [2, 1, 0]],  
[[4, 2, 0]],  
[[4, 2, 0]],  
[[4, 2, 0],[2, 1, 0]]  
]

var output = [];
scores.forEach(function(score) {
  var total = 0
  score.forEach(function(arr) {
    total += arr.reduce(function(a, b) { return Math.max(a, b); }); 
  })
  output.push(total);
})

console.log(output); // gives [4,4,4,6]

Upvotes: 1

Related Questions