skip to Main Content

I would like to insert element into 2nd and 9th position of an array for every 10 elements and the length of array can be vary.
I tried to use mod but the element will be inserted multiple time within 10 elements.

Example:

var array = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6','a7', 'a8', 'a9', 'a10','a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18', 'a19', 'a20', 'a21', 'a22', 'a23'];

Expected outcome (inserted b & c at position 2nd & 9th ):

[‘a1’, ‘b1‘, ‘a2’, ‘a3’, ‘a4’, ‘a5’, ‘a6′,’a7’, ‘c1‘, ‘a8’, ‘a9’, ‘b2‘, ‘a10′,’a11’, ‘a12’, ‘a13’, ‘a14’, ‘a15’, ‘c2‘, ‘a16’, ‘a17’, ‘b3‘, ‘a18’, ‘a19’, ‘a20’, ‘a21’, ‘a22’, ‘a23’];

How to achieve the result?

2

Answers


  1. const array = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18', 'a19', 'a20', 'a21', 'a22', 'a23'];
    const prefix = new Map([[1, 'b'], [8, 'c']]);
    const result = array.flatMap((element, index) => {
      const p = prefix.get(index % 10);
      if (p) {
        return [p + Math.ceil(index / 10), element];
      }
      return element;
    });
    console.log(result);
    Login or Signup to reply.
  2. You can iterate over the array while adding elements with Array#splice.

    const array = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6','a7', 'a8', 'a9', 'a10','a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18', 'a19', 'a20', 'a21', 'a22', 'a23'];
    const prefix = new Map([[1, 'b'], [8, 'c']]);
    for (let i = 0; i < array.length; i++) {
      const p = prefix.get(i % 10);
      if (p) array.splice(i, 0, p + Math.ceil(i / 10)), ++i;
    }
    console.log(array);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search