skip to Main Content

I have two Arrays they both have the same size and look like this:

a= [ 1, 2, 3, 2] and b = ['this', 'is', 'my', 'good example'].

Array a[i] defines how often the value of b[i] i want to write to a new Array. For my example the result would be c = ['this', 'is', 'is', 'my', 'my', 'my', 'good example', 'good example'].

I tried around with String.repeat but i dont know how to get it to an Array

3

Answers


  1. I think this solution will suit you

    const a = [1, 2, 3, 2];
    const b = ['this', 'is', 'my', 'good example'];
    
    const c = a.flatMap((count, i) => Array(count).fill(b[i]));
    
    console.log(c);
    Login or Signup to reply.
  2. You could just do a loop inside another loop to achieve that

    const a = [1, 2, 3, 2];
    const b = ['this', 'is', 'my', 'good example'];
    
    let array = [];
    b.forEach((x, i) => {
      for (let j = 0; j < a[i]; j++) {
        array.push(x);
      }
    })
    
    console.log(array)
    Login or Signup to reply.
  3. const a = [1, 2, 3],
          b = ['a','b','c']
    
    console.log(
      b.reduce((acc, item, idx) => acc.concat(Array(a[idx]).fill(item)), [])
    )
    
    // or the opposite
    
    console.log(
      a.reduce((acc, item, idx) => acc.concat(Array(item).fill(b[idx])), [])
    )

    I agree that flatMap is ideal for this task, as answered by @lvjonok

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search