Javascript - Combining a multidimensional array with an index

I have a multidimensional array that looks like this:

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

What I hope to accomplish is combining just one array, adding the array values ​​at its index.

Expected Result:

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

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

+4
source share
2 answers

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

, . ( , , , .)

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);

.

+3

: . .

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];
}
+2

Source: https://habr.com/ru/post/1629982/


All Articles