Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
How to create nested array of different length from a multidimensional array

I have an array that looks like this:

arr = [[1,2,3],
       [4,5,6],
       [7,8,9]]

I have initialized an empty array and I want put the diagonals of the arr inside the new array. So i've tried this:

arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
new_arr = [];
tail = arr.length - 1;
for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr[i].length; j++) {
    if (j == i) {
      new_arr.push(arr[i][j]);
    }
    if (j == tail) {
      new_arr.push(arr[i][j]);
      tail--;
    }
  }
}

console.log(new_arr)

The logic seems to work but I can't seem to get the structure right. What I want is to nest two arrays inside the new array like this:

[[1,5,9],[3,5,7]]

But what I get is one array with the right values unordered. How to get the expected output? Any help is appreciated. Thanks!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

var arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];


var diagonal1 = [];
var diagonal2 = [];

for (var i = 0; i < arr.length; i++) {
  diagonal1.push(arr[i][i]);
  diagonal2.push(arr[i][arr.length - i - 1]);
}

var new_arr = [diagonal1, diagonal2];
console.log(new_arr)

about 4 years ago · Juan Pablo Isaza Report

0

The following solution would work for you if the width and height of the number matrix is always equal.


const arr = [[1,2,3],
       [4,5,6],
       [7,8,9]];

const result = [[],[]];
arr.map((row,index) => {
  result[0].push(row[0+index]);
  result[1].push(row[row.length - index - 1]);
});


console.log(result); // [[1,5,9],[3,5,7]]
about 4 years ago · Juan Pablo Isaza Report

0

You need to have 2 separate temporary arrays. And you don't need nested loops. You can optimize the code like this with a single loop if you understand the math.

arr = [[1,2,3],
       [4,5,6],
       [7,8,9]];
       
function findDiagonals(arr) {
  const diagonal_1 = [];
  const diagonal_2 = [];
  
  for( let i = 0; i < arr.length; i++ ) {
    diagonal_1.push(arr[i][i]);
    diagonal_2.push(arr[i][arr.length - (i+1)]);
  }
  
  return [diagonal_1, diagonal_2];
}

console.log(findDiagonals(arr));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!