1

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]]

7 Answers 7

4

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))

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

Comments

3

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)
}

Comments

2

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);

Comments

2

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));

Comments

1

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)

Comments

1

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);

Comments

0

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)
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.