Reputation: 1
So I'm trying to generate an array that will have multiple objects, one of them with another array. Each object should have its own unique id, but when using for loop, each batch has objects with the same repeated ids. using i variable or even adding random number value seems to be not working. Is this even achievable in javascript?
Test.js
const testFunc = () => {
let resultArray = []
let testObj = {}
let testArray = []
const rn = () => {
return ~~(Math.random() * 1000)
}
for (let i = 0; i < 3; i++) {
testObj = { id: rn() }
testArray.push(testObj)
testObj = {}
}
for (let i = 0; i < 3; i++) {
resultArray.push(testArray)
}
console.log(resultArray)
return resultArray
}
Expected result:
[
[
{ id: 859, text: 0 },
{ id: 232, text: 1 },
{ id: 240, text: 2 },
{ id: 638, text: 3 },
{ id: 393, text: 4 }
],
[
{ id: 681, text: 0 },
{ id: 384, text: 1 },
{ id: 413, text: 2 },
{ id: 721, text: 3 },
{ id: 985, text: 4 }
],
[
{ id: 348, text: 0 },
{ id: 911, text: 1 },
{ id: 255, text: 2 },
{ id: 816, text: 3 },
{ id: 797, text: 4 }
]
]
Result I get:
[
[
{ id: 859, text: 0 },
{ id: 232, text: 1 },
{ id: 240, text: 2 },
{ id: 638, text: 3 },
{ id: 393, text: 4 }
],
[
{ id: 859, text: 0 },
{ id: 232, text: 1 },
{ id: 240, text: 2 },
{ id: 638, text: 3 },
{ id: 393, text: 4 }
],
[
{ id: 859, text: 0 },
{ id: 232, text: 1 },
{ id: 240, text: 2 },
{ id: 638, text: 3 },
{ id: 393, text: 4 }
]
]
Upvotes: 0
Views: 875
Reputation: 370679
You're only ever creating a single sub-array. The line
let testArray = []
only runs once, and you do
resultArray.push(testArray)
3 times - so in the result, all sub-arrays in resultArray
refer to the same testArray
.
Create a new array explicitly instead, and use a nested loop so that there are 3x3 iterations total:
let resultArray = []
let testObj = {}
const rn = () => {
return ~~(Math.random() * 1000)
}
for (let i = 0; i < 3; i++) {
const testArray = []
for (let i = 0; i < 3; i++) {
const testObj = {
id: rn()
}
testArray.push(testObj)
}
resultArray.push(testArray)
}
console.log(resultArray)
Upvotes: 0
Reputation: 191966
You push the testArray
thrice to the resultArray
. Instead generate testArray
in a loop, push it to the resultArray
, and add the items:
const testFunc = () => {
const resultArray = []
const rn = () => {
return ~~(Math.random() * 1000)
}
for (let i = 0; i < 3; i++) {
const testArray = []
resultArray.push(testArray)
for (let i = 0; i < 3; i++) {
const testObj = { id: rn() }
testArray.push(testObj)
}
}
return resultArray
}
console.log(testFunc())
Upvotes: 1