How do I remove a specific value from an array? Something like:
array.remove(value);
Constraints: I have to use core JavaScript. Frameworks are not allowed.
How do I remove a specific value from an array? Something like:
array.remove(value);
Constraints: I have to use core JavaScript. Frameworks are not allowed.
javascript
let fruits = ['apple', 'orange', 'banana', 'grape'];
// Find the index of the item you want to remove
let index = fruits.indexOf('banana');
// Use splice() to remove the item
fruits.splice(index, 1);
console.log(fruits); // Output: ['apple', 'orange', 'grape']
In the example above, we have an array called `fruits` with four elements. We want to remove the item 'banana' from the array.
First, we use the `indexOf()` method to find the index of 'banana' in the array. Then, we pass the index and the number `1` (the number of elements to remove) to `splice()`. This removes the item at the specified index from the array.
Finally, we log the updated array to the console, which now contains the 'banana' item removed.
Answered, September 11th, 2023
16361
Find the index
of the array element you want to remove using indexOf
, and then remove that index with splice
.
The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
array.splice(index, 1); // 2nd parameter means remove one item only
}
// array = [2, 9]
console.log(array);
The second parameter of splice
is the number of elements to remove. Note that splice
modifies the array in place and returns a new array containing the elements that have been removed.
For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of 5
from [2,5,9,1,5,8,5]
), while the second function removes all occurrences:
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
In TypeScript, these functions can stay type-safe with a type parameter:
function removeItem<T>(arr: Array<T>, value: T): Array<T> {
const index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
Answered, April 23rd, 2011
2379
Edited on 2016 October
In this code example I use array.filter(...)
function to remove unwanted items from an array. This function doesn't change the original array and creates a new one. If your browser doesn't support this function (e.g. Internet Explorer before version 9, or Firefox before version 1.5), consider polyfilling with core-js
.
Be mindful though, creating a new array every time takes a big performance hit. If the list is very large (think 10k+ items) then consider using other methods.
var value = 3
var arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(function(item) {
return item !== value
})
console.log(arr)
// [ 1, 2, 4, 5 ]
let value = 3
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => item !== value)
console.log(arr)
// [ 1, 2, 4, 5 ]
IMPORTANT ECMAScript 6 () => {}
arrow function syntax is not supported in Internet Explorer at all, Chrome before version 45, Firefox before version 22, and Safari before version 10. To use ECMAScript 6 syntax in old browsers you can use BabelJS.
An additional advantage of this method is that you can remove multiple items
let forDeletion = [2, 3, 5]
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => !forDeletion.includes(item))
// !!! Read below about array.includes(...) support !!!
console.log(arr)
// [ 1, 4 ]
IMPORTANT array.includes(...)
function is not supported in Internet Explorer at all, Chrome before version 47, Firefox before version 43, Safari before version 9, and Edge before version 14 but you can polyfill with core-js
.
If the "This-Binding Syntax" proposal is ever accepted, you'll be able to do this:
// array-lib.js
export function remove(...forDeletion) {
return this.filter(item => !forDeletion.includes(item))
}
// main.js
import { remove } from './array-lib.js'
let arr = [1, 2, 3, 4, 5, 3]
// :: This-Binding Syntax Proposal
// using "remove" function as "virtual method"
// without extending Array.prototype
arr = arr::remove(2, 3, 5)
console.log(arr)
// [ 1, 4 ]
Reference
Answered, December 19th, 2013
How do I undo the most recent local commits in Git?
How do I delete a Git branch locally and remotely?
How can I find all files containing a specific text (string) on Linux?
How to find all files containing specific text (string) on Linux?
How do I revert a Git repository to a previous commit?
How do I create an HTML button that acts like a link?
How do I check out a remote Git branch?
How do I force "git pull" to overwrite local files?
How to create npm package with definition files?
How to force page with dynamic AJAX elements to load completely
How can I export a Nextjs page as pdf?
What is the best way to automatically set jest timeout when debugging tests?
Is there a function like include where I can add two or more strings to search for?
Need to create an array of all keypaths of a JS nested dictionary
Querying between 2 values with a min and max
Decode .jpeg image from string