4

I have an multidimensional array which looks like this:

[  
  ["1","2","3","4"],
  ["1","2","3","4"],
  ["1","2","3","4"], 
  ["1","2","3","4"]  
]  

What I am hoping to accomplish is combining everything into a single array by adding the values of the array by its index.

Expected result:

[4,8,12,16] //(adding the 4 array values with appropriate index)

I see Lodash has a method _.zip, but that does not accept array of arrays as input to give the correct value. Is there an easy to accomplish this?

2 Answers 2

3

If _.zip does not accept array of arrays as input, there is a technical to achieve it. _.zip.apply(null, array).

It could be done like below. (Note your bottom level elements are strings, so there is one more step to convert them to number.)

var data =[  
  ["1","2","3","4"],
  ["1","2","3","4"],
  ["1","2","3","4"], 
  ["1","2","3","4"]  
];

var result = _.map(_.zip.apply(null, data), function (n) {
  return _.sum(_.map(n, function(x) { return +x; }));
}); 

console.log(result);

The demo.

Sign up to request clarification or add additional context in comments.

Comments

2

I'm interpreting your question as follows: map each element in the array to it's length plus the value of the previous element. Here is one way you could do that.

x = [  
  ["1","2","3","4"],
  ["1","2","3","4"],
  ["1","2","3","4"], 
  ["1","2","3","4"]  
]  
result = x.map(function(a) {
    return a.length;
}
for (i = 1; i < result.length; ++i) {
    result[i] += result[i - 1];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.