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

114
Views
Create two dimensional array from two arrays

I've got these two arrays and I need to obtain c. I managed to obtain a solution with two fors and conditionals, but I'm sure something better than O^2 can be obtained with JS.

a = [3, 2, 1, 3]
b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

c = [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i']]
about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

For fun purpose I wrote it in a coincisive way, hope you like it:

const a = [3, 2, 1, 3];
const b = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
const bClone = [...b];

const array = a.map((num, index) =>
  Array.from({ length: num }, () => bClone.shift())
);

console.log(array);

Of course controls should be added, thanks

about 4 years ago · Santiago Gelvez Report

0

I don't have that much good background in algorithms but I think this is better than two fors:

let a = [3, 2, 1, 3]
,b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

let head = 0

let result = a.map((e) => {
      let subArr = b.slice(head,head+e)   
      head +=e
      return subArr
  })
  
 console.log(result)

about 4 years ago · Santiago Gelvez Report

0

One possibility is to combine map with splice, taking care not to mutate the original array:

const a = [3, 2, 1, 3];
const b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];

function slices(sizes, arr){
  const clonedArr = [].concat(arr);     // clone array to prevent mutation 
  return sizes.map(size => clonedArr.splice(0,size));
}

console.log(slices(a,b));     // [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i']]

Alternatively, avoiding mutation altogether, you could use slice with a slightly convoluted reduce:

const slicesByReduce = (sizes, arr) => sizes
  .reduce(({start, acc}, size) => ({
    start: start + size,
    acc: [...acc, arr.slice(start, start + size)]
  }),{
    start: 0,
    acc: []
  }).acc;

console.log(slicesByReduce(a,b));     // [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i']]
about 4 years ago · Santiago Gelvez 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!