Home > Software design >  How can I add multi-dimensional arrays in javascript like this
How can I add multi-dimensional arrays in javascript like this

Time:09-23

I am working on a javascript mini-project where users have to enter a number.

That number is an endpoint of coordinates. Last coordinate I will store in my array will be in format of [number, number]

For example, that number is 3.

I have to store this in an array.

[1,1], [1,2], [1,3], [2,1], [2,2], [2,3], [3,1], [3,2], [3,3]

For example, if number is 4, array need to looks like this: [1,1], [1,2], [1,3], [1,4], [2,1], [2,2], [2,3], [2,4] [3,1], [3,2], [3,3], [3,4], [4,1], [4,2], [4,3], [4,4]

I hope you understand what I need. Any help?

CodePudding user response:

You just need two nested loops for this to work. In the code below, i variable represents the first number in the miniarray element, while j represents the second one. For each value of i, j will run n times and result in the array you want as follows:

let n = 3;
let arr = [];

for(let i=1; i<=n; i  ){
    for(let j=1; j<=n; j  ){
    arr.push([i, j]);
  }
}

console.log(arr);

CodePudding user response:

Please use the following javascript code snippet.

num = 5
arr=[]
for(i=1;i<=num;i  ){
  for(j=1;j<=num;j  ){
    temparr=[i,j]
    arr.push(temparr)
  } 
}
console.log(arr)

CodePudding user response:

hope this code helping you

const n = 5;
var array = Array(n).fill(0).map((o,index)=>o index 1);
array.map(o=>arr1.flatMap(e=>[[o,e]]));

CodePudding user response:

Using nested loops ... Try this one


function generateArray(int) {
  let array = [];
  let initial = 1;
  let numbers = [];
  while (initial <= int) {
    numbers.push(initial);
    initial  ;
  }
  let finalArr = [];
  numbers.forEach(number => {
    let i = 1;
    while (i <= numbers.length) {
      array.push([number, i]);
      i  ;
    }
  });
  return array;
}

console.log(generateArray(4))

  • Related