0

What is the most compact way of adding corresponding elements of multiple arrays of same length ?

var a = [1,2,3];
var b = [5,5,5];
var c = [1,1,1];
resultant array should be [7,8,9]

I can do this with a simple for loop but could it be possible for jquery/lodash solution with minimum lines of code?

Kamal Reddy
  • 2,610
  • 5
  • 28
  • 36

2 Answers2

0

Simple loop:

var result = [];
for(var i=0;i<3;i++)
 result.push(a[i]+b[i]+c[i]);

Note: Assuming all array of same length 3.

DEMO

Community
  • 1
  • 1
Manwal
  • 23,450
  • 12
  • 63
  • 93
0

Well i'm not sure what you mean by the word 'Compact', either reduced number of lines or increased performance.. but the most reasonable and recommended way of doing it is through a simple loop:

var a = [1,2,3];
var b = [5,5,5];
var c = [1,1,1];
var result = [];    
for(var i=0; i<a.length; i++){result[i] = a[i]+b[i]+c[i];}

result will contain [7,8,9]

Abdul Jabbar
  • 2,573
  • 5
  • 23
  • 43