1

Would I like to create a new array from the following :

Let array1 = [a,b,c,d]
let array2 = [x, y]

How to get new array like this [ay,bx,cy,dx]?

Thanks,

2 Answers 2

4

You could take the index with an offset and the remainder of the length of the second array.

let array1 = ['a','b','c','d'],
    array2 = ['x', 'y'],
    result = array1.map((v, i) => v + array2[(i + 1) % array2.length]);
 
console.log(result);

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

3 Comments

Great, thanks, but what if the elements are number, and I need to add array1 to array2?
it should work with numbers, too. what do you mean with "add array1 to array2"?
yes,result = array1.map((v, i) => parseInt(v) * parseInt( array2[(i) % array2.length] ));
0

You can use the modulus operator to get the correct second array elements:

let array1 = ['a','b','c','d'];
let array2 = ['x', 'y'];

let result = array1.map( (item, i) => { return item + array2[(i+1) % 2] } );

console.log(result);

Comments

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.