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

213
Views
How to create multiple array from single array?

I have a situation where I get the data in an array and I have to convert that to multiple arrays... Like Matrix.

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

the output should be:

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

this is what I have so far:

let i = 0;
const add = [];
while (i < list.length) {
  add.push([list[i], list[i + 2]]);
  i = i + 1;
}
return add;
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Maybe try this one?

let i = 0;
const list = [1,2,3,4,5,6,7,8,9]
const add = [];
let newarr =[]
while (i < list.length) {
  add.push([list[i], list[i + 2]]);
  add.push([list[i+1],list[i+3]])
  i +=4;
}
//remove undefined item from the array
newarr = add.map(arr=>arr.filter(item =>item != undefined)).filter(item=>item!="")


console.log(newarr)

about 4 years ago · Juan Pablo Isaza Report

0

const array = [1,2,3,4,5,6,7,8,9];
const visitedIndex = [];
const newArray = [];
array.forEach((element, i) => {
  if (!visitedIndex.includes(i)) {
    if (array[i+2]) {
      newArray.push([array[i], array[i+2]])
    } else {
      newArray.push([array[i]])
    }
    visitedIndex.push(i);
    visitedIndex.push(i+2);
  };

});

about 4 years ago · Juan Pablo Isaza Report

0

Lodash chunk if you don't mind.

Or you can use recursive approach in vanila js.

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

const chunk = (arr, n) => arr.length ? [arr.slice(0, n), ...chunk(arr.slice(n), n)] : [];

console.log(chunk(array, 2));
.as-console-wrapper{min-height: 100%!important; top: 0}

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!