Remove an item by index position 1

Remove an item by index position

let vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']
console.log(vegetables)
// ["Cabbage", "Turnip", "Radish", "Carrot"]

let pos = 1
let n = 2

let removedItems = vegetables.splice(pos, n)
// this is how to remove items, n defines the number of items to be removed,
// starting at the index position specified by pos and progressing toward the end of array.

console.log(vegetables)
// ["Cabbage", "Carrot"] (the original array is changed)

console.log(removedItems)
// ["Turnip", "Radish"]

Here is what the above code is Doing:
1. The splice() method is used to change the contents of an array by removing or replacing existing elements and/or adding new elements in place.
2. The first argument specifies the location at which to begin adding or removing elements.
3. The second argument specifies the number of elements to remove.
4. The third and subsequent arguments are optional; they specify elements to be added to the array.

Similar Posts