-1
let array1 = [1,2,3,4,5]
let array2 = [6,7,8,9,10]
let array3 = [ {x: array1, y: array2} ]

How to write correctly loop, so in output I will get 1 array with 5 ojects inside?

//Expected output

[ {x: 1, y: 6}, {x: 2, y: 7}, {x: 3, y: 8}, {x: 4, y: 9}, {x: 5, y: 10}]
2
  • It should be obvious that you need a loop. Commented Jul 1, 2022 at 20:22
  • 1
    Can you maybe suggest the way you would loop through it? The variable array3 may bring some confusion. Commented Jul 1, 2022 at 20:24

1 Answer 1

1

You should loop through all the values of the first array with .map which generates a new array. The function inside of .map takes the value from array1 as value and array2 as array2[index];

let array1 = [1,2,3,4,5]
let array2 = [6,7,8,9,10]
let array3 = array1.map(function (value, index) {
    return {x: value, y: array2[index]}
})
console.log(array3);

I've intentionally used slightly more verbose solution that could be required for easier readability and understanding.

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

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.