JavaScript: Remove a specific item from an Array
Posted on Jun 15, 2020
Although this is not a problem - many programmers have difficulty removing an element from an array into JavaScript. To remove an item from an array, you can use special methods, such as:
shift – the method will remove the element from the beginning of the array.
splice – this method removes the element from the middle of the array.
pop – this method removes the element from the end of the array.
With the splice method, you can remove elements, insert elements, and replace elements.
Example:
arr.splice(start[, countDelete[, elemInsert1, ..., elemInsertN]])
Removal of an element from an array:
let arr = ["Hello", "World", "Forest"]; arr.splice(1, 1); // starting from position 1, delete 1 item console.log(arr); // ["Hello", "Forest"]
let arr = ["Hello", "World", "Galaxy", "David"] arr.splice(0, 3, "Hey!") console.log(arr) // ["Hey!", "David"]
Remove a specific item from an array:
const array = [1, 2, 3]; const index = array.indexOf(2); if (index > -1) { array.splice(index, 1); } console.log(array); // [1, 3]
Removing item (ECMAScript 6 code):
let value = 7 let arr = [1, 2, 7, 4, 5, 7] arr = arr.filter(item => item !== value) console.log(arr) // [ 1, 2, 4, 5]
Removing multiple items (ECMAScript 7 code):
let forDelete = [2, 3, 5] let arr = [1, 2, 3, 4, 5, 3] arr = arr.filter(item => !forDelete.includes(item)) console.log(arr) // [ 1, 4 ]
ES6 & without mutation:
const removeByIndex = (list, index) => [ ...list.slice(0, index), ...list.slice(index + 1) ]; output = removeByIndex([11, 22, 33, 44], 1) //=> [11, 33, 44] console.log(output)
Leave a comment: