Joer
Joer

Reputation: 73

How to add arrays into an array in JavaScript

How could I achieve this below in JavaScript. I tried searching for it on MDN but couldn't find any method for it.

let a, b
let allNumbers = []

for (a = 10; a < 60; a = a + 10) {
    for (b = 1; b <= 3; b++) {
        allNumbers.push(a + b)
    }
}

The desired outcome is an array inside the allNumbers array:

[[11,12,13], [21,22,23], [31,32,33], [41,42,43], [51,52,53]]

Upvotes: 1

Views: 745

Answers (7)

Alex Char
Alex Char

Reputation: 33218

You can try:

const result = Array(5).fill(1).map((a, i) => Array(3).fill(1).map((a, j) => +`${i+1}${j+1}`));
console.log(JSON.stringify(result));

Upvotes: 2

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48337

You have to use one second array.

let a, b
let allNumbers = []

for (a = 10; a < 60; a = a + 10) {
    second = [];
    for (b = 1; b <= 3; b++) {
        second.push(a + b);
    }
    allNumbers.push(second)
}
console.log(allNumbers);

You can apply a shorted version using ES6 features.

allNumbers = []
for (a = 10; a < 60; a = a + 10) {
    allNumbers.push([...Array(3)].map((_, i) => i + a + 1))
}
console.log(allNumbers);

Upvotes: 2

Sudhir Ojha
Sudhir Ojha

Reputation: 3305

You need to declare a second array inside your loop. Like following:

let a, b
let allNumbers = []

for (a = 10; a < 60; a = a + 10) {
    var tempArray = [];
    for (b = 1; b <= 3; b++) {
        tempArray.push(a + b)
    }
    allNumbers.push(tempArray);
}
console.log(allNumbers);

Upvotes: 1

Alexander Moser
Alexander Moser

Reputation: 457

Just create an array and push the new array int allNumbers:

...
let c = []
for (b = 1; b <= 3; b++) {
    c.push(a + b)
}
allNumbers.push(c)
...

Upvotes: 0

Luca Kiebel
Luca Kiebel

Reputation: 10096

Just create a temporary Array in the outer loop and push the elements from the inner loop into it, after the inner Loop is finished, push the temporary array in the main one:

let a, b
let allNumbers = []

for (a = 10; a < 60; a += 10) {
    let someNumbers = [];
    for (b = 1; b <= 3; b++) {
        someNumbers.push(a + b)
    }
    allNumbers.push(someNumbers)
}

console.log(JSON.stringify(allNumbers))

Upvotes: 4

michaelitoh
michaelitoh

Reputation: 2340

You have to create a new array an add the element to it in the second loop and the add this array to the final one after the second loop.

let a, b
let allNumbers = []

for (a = 10; a < 60; a = a + 10) {
  data = []
  for (b = 1; b <= 3; b++) {
    data.push(a + b)
  }
  allNumbers.push(data)
}

console.log(allNumbers)

Upvotes: 1

ashish singh
ashish singh

Reputation: 6904

how about this

var a, b
var allNumbers = []

for (a = 10; a < 60; a = a + 10) {
    var part = [];
    for (b = 1; b <= 3; b++) {
        part.push(a + b)
    }
    allNumbers.push(part)
}

Upvotes: 3

Related Questions