DEV Community

Raphael Chaula
Raphael Chaula

Posted on

How to insertAt, removeAt and remove an element in array JavaScript

Suppose [0, 1, 2, 3, 4, 5, 6] is your array and you want to insert another value at a centain index (replace) in it or you want to remove a value at a certain index from it or you just want to remove a certain value lets say 5 out of it, here is what you can do in JavaScript.

insertAt

let numbers = [0, 1, 2, 3, 4, 5, 6]; const insertAt = (element, index) => { numbers.splice(index, 1, element) } insertAt(7, 1); console.log(numbers); 
Enter fullscreen mode Exit fullscreen mode

When you run the script the out put will be [ 0, 7, 2, 3, 4, 5, 6 ]
Element 1 is replaced with 7

removeAt

let numbers = [0, 1, 2, 3, 4, 5, 6]; const removeAt = (index) => { numbers.splice(index, 1); }; removeAt(1); console.log(numbers); 
Enter fullscreen mode Exit fullscreen mode

When you run the script the out put will be [ 0, 2, 3, 4, 5, 6 ]
Element at index 1 is removed from numbers.

removeElement

let numbers = [0, 1, 2, 3, 4, 5, 6]; const removeElement = (element) => { const index = numbers.indexOf(element); if (index > -1) { numbers.splice(index, 1); } else { throw new Error('Element not found in array'); } } removeElement(5); console.log(numbers); 
Enter fullscreen mode Exit fullscreen mode

When you run the script the out put will be [ 0, 1, 2, 3, 4, 6 ]
Element 5 is removed from numbers.
If you run removeElement(9) it will throw an error - Element not found in array because 9 is not in the numbers array.

Happy hacking!

Top comments (0)