I am new to this so sorry if the question is dumb I have two arrays, one is an array x values and the other one for y values. I need to make an array that contains both, like [x1,y1,x2,y2...]; how do I make this using loops?
Asked
Active
Viewed 29 times
-1
-
Does this answer your question? [How do I zip two arrays in JavaScript?](https://stackoverflow.com/questions/22015684/how-do-i-zip-two-arrays-in-javascript) – Marcos Blandim Nov 03 '21 at 17:48
-
So would your x-values be the even indices in your array and the y-values the odd indices? Or would an array of Objects work? `[{x:x1,y:y1},{x:x2,y:y2}...[x:xn,y:yn}]` – mykaf Nov 03 '21 at 17:49
2 Answers
2
If both the arrays contain the same number of elements then
let arr = []
let xArr = [/*xValues*/]
let yArr = [/*yValues*/]
for (let i = 0; i < xArr.length; i++) {
arr.push(xArr[i])
arr.push(yArr[i])
}

SPARTACUS5329
- 133
- 10
0
What about objects?
var myObj = {
x: [
"1",
"2"
],
y: [
"1",
"2"
]
}
You can select it by:
myObj.x[0];
// "1"
myObj.x[1];
// "2"
myObj.y[0];
// "1"
myObj.y[1];
// "2"
Also, we all wonder things as programmers. Your question is not dumb for being curious.

Parking Master
- 551
- 1
- 4
- 20