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?

1
  • 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] ) Commented Jan 21, 2020 at 5:50

4 Answers 4

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

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

Comments

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

Comments

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)

Comments

0

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.