-1

How to collect elements from an array?

Example:

array1 = [1,2,3,4,5], array2 = [6,7,8,9,10] and the results creates a new array with the result [7,9,11,13,15]

arrayy = () => {

  var arr1 = [1, 2, 3, 4, 5];
  var arr2 = [6, 7, 8, 9, 10];
  var test = " "
  for (var i = 0; i < arr1.length; i++) {
    test += (arr1[i] + arr2[i]);

  }
  console.log(test);
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 4
    How is setting up a server related to the JS arrays? – Teemu Aug 20 '19 at 11:32
  • @briosheje I see it was deleted by Tarchy and and not community - or perhaps I do not see the votes – mplungjan Aug 20 '19 at 11:51
  • Please visit [help], take [tour] to see what and [asl]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output. – mplungjan Aug 20 '19 at 11:54
  • @mplungjan yep, just wanted to make sure that the repost chain would end there, though :P – briosheje Aug 20 '19 at 11:54

3 Answers3

3

You need to use array and push the value into it, instead of appending it to string

const arrayy = () => {

  var arr1 = [1, 2, 3, 4, 5];
  var arr2 = [6, 7, 8, 9, 10];
  var test = []                            //  <-- initialize as array
  for (var i = 0; i < arr1.length; i++) {
    test.push(arr1[i] + arr2[i]);          // <-- push values to array 
  }
  console.log(test);
}

arrayy()
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

Your test variable should be an array which you .push() your results to. Instead, you could .map() one array's elements to the addition of the others array's element of the same index like so:

const add_arrays = (arr1, arr2) => 
  arr1.map((n, i) => n+arr2[i]);

const array1 = [1,2,3,4,5];
const array2 = [6,7,8,9,10];

console.log(add_arrays(array1, array2)); // [7, 9, 11, 13, 15]
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
1

Assuming both arrays will always have the same length, we can do it using Array.prototype.reduce:

const array1 = [1,2,3,4,5];
const array2 = [6,7,8,9,10];

const res = array1.reduce((acc, ele, idx) => {
  return acc.concat(ele + +array2[idx]);
}, []);

console.log(res);
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44