I feel like this should be easier to find online, but I haven't been able to find anything about it.
So my question is, can I use the total amount from an existing array to build that many separate arrays and auto populate them?
Can you Build Multiple Arrays using a For Loop based on the value amount of an existing array?
var arrA = ["box 1", "box 2", "box 3"];
for (i = 0; i < arrA.length; i++) {
var arr[i] =[
"Style[i]",
"ListA[i]",
"ListB[i]"
];
}
This doesn't work, but the result I am looking for is an output like this
var arr1 = ["Style1","ListA1","ListB1"];
var arr2 = ["Style2","ListA2","ListB2"];
. . . .
and continue repeating for the amount of times based on the Array length?
4 Answers 4
You are looking for this ?
const arrA = ["box 1", "box 2", "box 3"];
const arrB = arrA.map((c,i)=>[`Style${i+1}`,`ListA${i+1}`,`ListB${i+1}`])
console.log( arrB )
2 Comments
What about a function that takes the original, and the new array in, and returns the result.
let addArray = (original, newArray) => {
let result = original.push(newArray)
return result
}
//Not sure what's meant by auto-populating them...But this
//Will take an array of arrays, and simply push "newArray" into
// "original" array of arrays.
Comments
If I understood you right, you want to dynamically create some arrays from a given array. I think you can do it this way
let arrA = ["box 1", "box 2", "box 3"];
let generatedArrays = {};
for (let i = 0 ; i< arrA.length ; i++){
generatedArrays[arrA[i]] = []
}
console.log(generatedArrays)
1 Comment
You can implement this by creating two functions, one to initialize the first list of arrays (called once, at the beginning) and the one one is called every time you add a new item to the first array as so:
//first (master) array
var arrA = ["box 1", "box 2", "box 3"];
//array to hold individual box's array
var arrBoxes = []
function createInitArrays() {
for (i = 0; i < arrA.length; i++) {
arrBoxes[i] = [
"Style" + (i + 1),
"ListA" + (i + 1),
"ListB" + (i + 1)
];
}
}
function createNewArray() {
var index = arrA.length
arrBoxes[index] = [
"Style" + (index+1),
"ListA" + (index+1),
"ListB" + (index+1)
];
}
//call to create initial arrays
createInitArrays()
// call to create new array every time you update 'arrA'
// createNewArray()
// display list of arrays based on 'arrA'
console.log(arrBoxes)
var arrA = ["box 1", "box 2", "box 3", "box 4"];done.