❌ Removing items from arrays
06 Jan, 2021
👋 FYI, this note is over 6 months old. Some of the content may be out of date.
On this page
Remove single item from array Jump to heading
const removeItemFromArray = (arr, value) => {
var index = arr.indexOf(value)
if (index > -1) {
arr.splice(index, 1)
}
return arr
}
// Usage
console.log(removeItemFromArray([2, 5, 9, 1, 5, 8, 5], 5))
Remove multiple items from array Jump to heading
const removeAllItemsFromArray = (arr, value) => {
var i = 0
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1)
} else {
++i
}
}
return arr
}
// Usage
console.log(removeAllItemsFromArray([2, 5, 9, 1, 5, 8, 5], 5))
← Back home