Concatenate two arrays according to their respective indices

Asked

Viewed 75 times

1

I have two arrays, the first being [a, c, e, g] and the second [b, d, f, h], for example.

I want to concatenate these two arrays into a respective order, forming: [ab, cd, Ef, Gh] instead of the standard Concat, which would be [a, c, e, g, b, d, f, h]. That is, the element of index 0 of the second array, I want it to join element 0 of the first array, and element 1 of the second array, I want it to join element 1 of the first array, so respectfully.

What I tried: Reduce, map and foreach. Because I’m still a beginner in programming logic, I couldn’t get the idea out of the paper.

My code is two inputs. Each array I have shown of example represents the respective values of my inputs (the first array represents the first input and the second, the second). Since the array starts with a blank value, '', because the user who will type its value and display it on the screen, I was unable to perform one for each index, since it is an oscillating array. In a part of the screen, I have a span that will show the value of this new array that I crave.

  • "What I tried: Reduce, map and foreach" puts in question what already tried

  • What’s the point? I tried and it went wrong '-'

  • If I put what I tried I’d have to fill about 30 lines of ugly code

2 answers

3


Just make a for and join the elements.

var array1 = ['a','c','e','g']
var array2 = ['b','d', 'f', 'h']

var array3 = []

for(let i in array1){
    array3.push(array1[i]+array2[i])
}

console.log(array3)

  • 1

    Thank you very much, young man.

2

You can merge two arrays of the same length using the method Array.prototype.map() to create an array the element n is a string composed of elements n of L1 and L2.

l1 = ["a", "c", "e", "g"]
l2 = ["b", "d", "f", "h"]

//e= elemento, i= índice
l3 = l1.map((e, i) => `${e}${l2[i]}`);

console.log(l3);

Or use Array.prototype.reduce() passing an empty array as starting value and with Array.prototype.push() Insert the result between the data.

l1 = ["a", "c", "e", "g"]
l2 = ["b", "d", "f", "h"]

//r= resultado, e= elemento, i= índice
l3 = l1.reduce((r, e, i)=>{
  r.push(`${e}${l2[i]}`);
  return r
},[]);

console.log(l3);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.