0

I would like to join the values of 2 equal sized arrays and build a 3rd array similar to desired array below. Please advice as i am unable to find a javascript built-in method for this. The purpose of building this array is to create an array of custom primary keys.

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

Desired array3 = ['ad', 'be', 'cf']

2 Answers 2

2

Something like this should work:

const array1 = ['a', 'b', 'c']
const array2 = ['d', 'e', 'f']
const array3 = array1.map((it, i) => it + array2[i])
console.log(array3)

The above will map each item in the first array, adding the item at the same index from the second one.

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

Comments

1

You can try a basic for loop:

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

for (let i = 0; i < array1.length; i++) {
  const curr1 = array1[i];
  const curr2 = array2[i];

  final.push(`${curr1}${curr2}`)
}

console.log(final)

Or a one liner:

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const final = array1.map((val, index) => array1[index] + array2[index])

4 Comments

I liked how you edited your question and stole my work =)
Sorry? i did not edit the question. Could you pls explain?
HI @Cyclonecode, I am sorry if it seemed I like copied your work, but truthfully, I did not copy it. I just created the easiest solution first then refactored it.
I was just kidding although I would not say the first solution is the easiest, more complex and a simple map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.