Skip to content

Inserting and removing elements at a particular position from a JavaScript array

Let’s define an array in JavaScript.

let nums = [1, 2, 3, 5, 6];

Let’s say I would like to insert an element at the fourth position in this array.

const insertAt = (nums, element, index) => {
    nums.splice(index, 1, element)
}

insertAt(nums, 4, 3); //insert 4 at the 4th position. index for fourth position is 3
console.log(nums); //[1, 2, 3, 4, 6]
Advertisements

To remove an element at an index we can follow similar approach.

const removeAt = (nums, index) => {
    nums.splice(index, 1);
};

removeAt(nums, 1);
console.log(nums);  //[1, 3, 5, 6]
See also  null vs undefined vs NaN in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.