0

I'm trying to combine the array elements of two array to create a new combined elements array. Here is what I'm doing.

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];

var arr = [];

for(let i=0; i< array1.length;i++){
    for(let j=0; j < array2.length;j++){
        arr.push(array1[i]+array2[j])
    }
}

Here is the result I'm getting.

["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]

But the expected result is

['ad','be','cf']

How can I achieve this? Where should I apply the break statement?

Musthafa
  • 542
  • 1
  • 9
  • 25
  • for(let i=0; i< array1.length;i++){ arr.push(array1[i]+array2[i]) }. But you can simplify it with a map: var arr= array1.map((v,i)=> array1[i] + array2[i] ) – Mayra Navarro Jan 21 '20 at 05:50

4 Answers4

2

Don't use a nested loop - instead, use .map on one of the arrays, access the same index in the other array and concatenate:

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];

const combined = array1.map((char, i) => char + array2[i]);
console.log(combined);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

You need one loop, not nested

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];

const newArray = [];
for(let i=0; i<array1.length; i++){
  newArray.push(array1[i]+array2[i])
}
console.log(newArray);

Alternatively, you can use Array.prototype.map. It will iterate over one array and returns a new array based on passed callback.

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];

const newArray = array1.map((e,i) => e+array2[i]);

console.log(newArray);
Archie
  • 901
  • 4
  • 11
0

Use reduce

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
var a=array1.reduce((acc,e)=>{
acc.push(e+array2[array1.indexOf(e)])
return acc
},[])
console.log(a)
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

var array1 = ["a", "b", "c"];
var array2 = ["d", "e", "f"];

var newArray = array1.map((e, i) => e + array2[i]);
console.log(newArray);