skip to Main Content

I had to achieve a quite specific task and as far as I checked I didn’t find existing solutions in there so I’m gonna share my work if it helps (I really hope I’m not issuing a duplicate, I found this question Shift array to right by adding a new element to left using js which is not really my goal)

I had to insert an element in an array at a given position, and shift the rest to keep the same order and length. For example:

let array = ['a', 'b', 'd', 'e', 'f'];
const idx = 2;
const new = 'c';

Then the expected output is ['a', 'b', 'c', 'd', 'e']

The question is now: how to proceed, without creating copies and explicitly looping the whole input array ?

3

Answers


  1. Chosen as BEST ANSWER

    So, I came up with this solution ─ don't hesitate to tell if there's a better way to do this !

    let array = ['a', 'b', 'd', 'e', 'f'];
    const idx = 2;
    const new = 'c';
    
    array.splice(idx, months.length-idx, new).forEach((e, i, a) => {
      if (i < a.length-1) {
        months.push(e);
      }
    });
    

    splice returns an array with the removed elements: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

    forEach takes (element, index, array upon which forEach is called) as parameters: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach


  2. You could splice the array and adjust the length.

    const
        array = ['a', 'b', 'd', 'e', 'f'],
        index = 2,
        value = 'c';
    
    array.splice(index, 0, value);
    array.length--;
    
    console.log(array);
    Login or Signup to reply.
  3. As an alternative to Array::splice() you can use Array::copyWithin():

    const
        array = ['a', 'b', 'd', 'e', 'f'],
        index = 2,
        value = 'c';
    
    array.copyWithin(index + 1, index);
    array[index] = value;
    
    console.log(array);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search