DEV Community

miku86
miku86

Posted on

Diary - 2018.09.04

Today a really simple snippet.

Inserting an item into an existing array:

let myFruits = ["apple", "orange", "strawberry"];
myFruits.splice(1, 0, "banana");
console.log(myFruits); // [ 'apple', 'banana', 'orange', 'strawberry' ]
Enter fullscreen mode Exit fullscreen mode

Explanation:

array.splice(index, 0, item)
Enter fullscreen mode Exit fullscreen mode

at index, delete 0 items and insert item at this position.

So with splice, we can delete and insert.

Read more @MDN

Top comments (0)