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

115
Views
How to create a new array based on the number of sub arrays in js

Here is my first array:

const withSub = [[31, 32, 34, 34], [32, 36], [12], [15, 38]];

Here is my second array:

const arr = ['f', 'b', 'c', 'd'];

The number of arrays in withSub is always equal to the number of arr arrays, while the number of subarrays in withSub may be different.

I want to create a function that generates a new array based on these two arrays in such a way that the number of each element in arr must be equal to the number of subarrays in withArr.

In this example the final array must be:

   ['f', 'f', 'f', 'f', 'b', 'b', 'c', 'd', 'd'];
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

If I understood your question correctly, you can use .flatMap() on your withSub array to map each number within each subarray to their corresponding letter from arr. You can do this by taking the index of the subarray from the flatMap callback, and then use that to obtain the letter from arr when mapping your subarrays.

See example below:

const withSub = [[31, 32, 34, 34], [32, 36], [12], [15, 38]];
const arr = ['f', 'b', 'c', 'd'];

const res = withSub.flatMap((subArr, i) => subArr.map(() => arr[i]));
console.log(res);

about 4 years ago · Juan Pablo Isaza Report

0

you can do something as the following code:

const generate = (numbers, letters) => {
  return numbers.map((nums, i) => {
    return nums.map(num => letters[i])
  }).flat()
}

And then use it with generate(withSub, arr).

about 4 years ago · Juan Pablo Isaza Report

0

You can have an approach with forEach() and spread operator.

forEach() is similar to a forloop with subtle differences.

const awesomeFunction = (withSub , arr) => {
let ans = [];

arr.forEach( (x,index) => {
     let newArr = new Array(withSub[index].length).fill(x);  
     
     ans = [...ans , ...newArr];  
});

return ans; };

const withSub = [[31, 32, 34, 34], [32, 36], [12], [15, 38]];
const arr = ['f', 'b', 'c', 'd'];


console.log(awesomeFunction(withSub,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!