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.
If you must support older versions of Internet Explorer, I recommend using the following polyfill (note: this is not a framework). It's a 100% backwards-compatible replacement of all modern array methods (JavaScript 1.8.5 / ECMAScript 5 Array Extras) that works for Internet Explorer 6+, Firefox 1.5+, Chrome, Safari, & Opera.
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
For anyone looking to replicate a method that will return a new array that has duplicate numbers or strings removed, this has been put together from existing answers:
function uniq(array) {
var len = array.length;
var dupFree = [];
var tempObj = {};
for (var i = 0; i < len; i++) {
tempObj[array[i]] = 0;
}
console.log(tempObj);
for (var i in tempObj) {
var element = i;
if (i.match(/\d/)) {
element = Number(i);
}
dupFree.push(element);
}
return dupFree;
}
John Resig posted a good implementation:
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
If you don’t want to extend a global object, you can do something like the following, instead:
// Array Remove - By John Resig (MIT Licensed)
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
But the main reason I am posting this is to warn users against the alternative implementation suggested in the comments on that page (Dec 14, 2007):
Array.prototype.remove = function(from, to) {
this.splice(from, (to=[0, from || 1, ++to - from][arguments.length]) < 0 ? this.length + to : to);
return this.length;
};
It seems to work well at first, but through a painful process I discovered it fails when trying to remove the second to last element in an array. For example, if you have a 10-element array and you try to remove the 9th element with this:
myArray.remove(8);
You end up with an 8-element array. I don't know why, but I confirmed John's original implementation doesn't have this problem.
splice()
: removes an item with a specified index.
filter()
: removes an item with a specified value.
pop()
: removes the item at the end of the array.
shift()
: removes the item at the start of the array.
I've created a snippet to demonstrate each of these specific methods.
let simpleArray = [1, 2, 3, 4, 5];
document.getElementById('result').innerText = `Simple Array: ${simpleArray}`;
// Remove by index using splice()
function removeByIndexSplice(array) {
let indexToRemove = parseInt(document.getElementById('indexToRemoveSplice').value);
array.splice(indexToRemove, 1);
document.getElementById('result').innerText = `Array after removal: ${array}`;
}
// Remove by value using filter()
function removeByValueFilter(array) {
let valueToRemove = parseInt(document.getElementById('valueToRemoveFilter').value);
array = array.filter(item => item !== valueToRemove);
document.getElementById('result').innerText = `Array after removal: ${array}`;
}
// Remove last item using pop()
function removeLastItemPop(array) {
array.pop();
document.getElementById('result').innerText = `Array after removal: ${array}`;
}
// Remove first item using shift()
function removeFirstItemShift(array) {
array.shift();
document.getElementById('result').innerText = `Array after removal: ${array}`;
}
body {
display: flex;
flex-flow: column nowrap;
}
<!DOCTYPE html>
<html>
<body>
<h1>Simple ways to remove an item from an Array</h1>
<div>
<h2>splice()</h2>
<label for="indexToRemoveSplice">Enter index to Remove:</label>
<input type="number" id="indexToRemoveSplice">
<button onclick="removeByIndexSplice(simpleArray)">Remove Item</button>
</div>
<div>
<h2>filter()</h2>
<label for="valueToRemoveFilter">Enter value to Remove:</label>
<input type="number" id="valueToRemoveFilter">
<button onclick="removeByValueFilter(simpleArray)">Remove Item</button>
</div>
<div>
<h2>pop()</h2>
<button onclick="removeLastItemPop(simpleArray)">Remove Last Item</button>
</div>
<div>
<h2>shift()</h2>
<button onclick="removeFirstItemShift(simpleArray)">Remove First Item</button></div>
<p id="result"></p>
</body>
</html>
You can filter out with array.filter.
const arr=['a','b','c','d','e']
const newArray = arr.filter(v => v!='a');
console.log(newArray); // ['b', 'c', 'd', 'e']
Or you could remove several items
const newArray = arr.filter(v => !['a', 'b'].some(t => t == a));
console.log(newArray) // ['c', 'd', 'e']
Will create a copy of the original array:
array.filter(num => num !== valueToRemove);
Using filter and reasigning to the original array will maintain the same reference:
array = array.filter(num => num !== valueToRemove);
Using indexOf changes the contents of original array without creating a new array.
array.splice(indexOf(valueToRemove), 1);
All three options have a time complexity of O(n).
Your question is about how to remove a specific item from an array. By specific item you are referring to a number eg. remove number 5 from array. From what I understand you are looking for something like:
// PSEUDOCODE, SCROLL FOR COPY-PASTE CODE
[1,2,3,4,5,6,8,5].remove(5) // result: [1,2,3,4,6,8]
As for 2021 the best way to achieve it is to use array filter function:
const input = [1,2,3,4,5,6,8,5];
const removeNumber = 5;
const result = input.filter(
item => item != removeNumber
);
The above example uses array.prototype.filter function. It iterates over all array items, and returns only those satisfying the arrow function. As a result, the old array stays intact, while a new array called result
contains all items that are not equal to five. You can test it yourself online.
You can visualize array.prototype.filter like this:
Code quality
Array.prototype.filter
is far the most readable method to remove a number in this case. It leaves little place for mistakes and uses core JS functionality.
Why not array.prototype.map
?
Array.prototype.map
is sometimes considered as an alternative for array.prototype.filter
for that use case. But it should not be used. The reason is that array.prototype.filter is conceptually used to filter items that satisfy an arrow function (exactly what we need), while array.prototype.map is used to transform items. Since we don't change items while iterating over them, the proper function to use is array.prototype.filter
.
Support
As of today (11.4.2022) 94,08% of Internet users' browsers support array.prototype.filter. So generally speaking it is safe to use. However, IE6 - 8 does not support it. So if your use case requires support for these browsers there is a nice polyfill made by Chris Ferdinanti.
Performance
Array.prototype.filter
is great for most use cases. However if you are looking for some performance improvements for advanced data processing you can explore some other options like using pure for
. Another great option is to rethink if the array you are processing really has to be so big. It may be a sign that the JavaScript should receive a reduced array for processing from the data source.
A benchmark of the different possibilities: https://jsben.ch/C5MXz
This is my simple code to remove specific data in an array using the splice method. The splice method will be given two parameters. The first parameter is the start number, and the second parameter is deleteCount. The second parameter is used for removing some element start from the value of the first parameter.
let arr = [1, 3, 5, 6, 9];
arr.splice(0, 2);
console.log(arr);
Create new array:
var my_array = new Array();
Add elements to this array:
my_array.push("element1");
The function indexOf (returns index or -1 when not found):
var indexOf = function(needle)
{
if (typeof Array.prototype.indexOf === 'function') // Newer browsers
{
indexOf = Array.prototype.indexOf;
}
else // Older browsers
{
indexOf = function(needle)
{
var index = -1;
for (var i = 0; i < this.length; i++)
{
if (this[i] === needle)
{
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle);
};
Check index of this element (tested with Firefox and Internet Explorer 8 (and later)):
var index = indexOf.call(my_array, "element1");
Remove 1 element located at index from the array
my_array.splice(index, 1);
You can do a backward loop to make sure not to screw up the indexes, if there are multiple instances of the element.
var myElement = "chocolate";
var myArray = ['chocolate', 'poptart', 'poptart', 'poptart', 'chocolate', 'poptart', 'poptart', 'chocolate'];
/* Important code */
for (var i = myArray.length - 1; i >= 0; i--) {
if (myArray[i] == myElement) myArray.splice(i, 1);
}
console.log(myArray);
A friend was having issues in Internet Explorer 8 and showed me what he did. I told him it was wrong, and he told me he got the answer here. The current top answer will not work in all browsers (Internet Explorer 8 for example), and it will only remove the first occurrence of the item.
function removeAllInstances(arr, item) {
for (var i = arr.length; i--;) {
if (arr[i] === item) arr.splice(i, 1);
}
}
It loops through the array backwards (since indices and length will change as items are removed) and removes the item if it's found. It works in all browsers.
If you want a new array with the deleted positions removed, you can always delete the specific element and filter out the array. It might need an extension of the array object for browsers that don't implement the filter method, but in the long term it's easier since all you do is this:
var my_array = [1, 2, 3, 4, 5, 6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';}));
It should display [1, 2, 3, 4, 6]
.
I'm pretty new to JavaScript and needed this functionality. I merely wrote this:
function removeFromArray(array, item, index) {
while((index = array.indexOf(item)) > -1) {
array.splice(index, 1);
}
}
Then when I want to use it:
//Set-up some dummy data
var dummyObj = {name:"meow"};
var dummyArray = [dummyObj, "item1", "item1", "item2"];
//Remove the dummy data
removeFromArray(dummyArray, dummyObj);
removeFromArray(dummyArray, "item2");
Output - As expected. ["item1", "item1"]
You may have different needs than I, so you can easily modify it to suit them. I hope this helps someone.
Based on all the answers which were mainly correct and taking into account the best practices suggested (especially not using Array.prototype directly), I came up with the below code:
function arrayWithout(arr, values) {
var isArray = function(canBeArray) {
if (Array.isArray) {
return Array.isArray(canBeArray);
}
return Object.prototype.toString.call(canBeArray) === '[object Array]';
};
var excludedValues = (isArray(values)) ? values : [].slice.call(arguments, 1);
var arrCopy = arr.slice(0);
for (var i = arrCopy.length - 1; i >= 0; i--) {
if (excludedValues.indexOf(arrCopy[i]) > -1) {
arrCopy.splice(i, 1);
}
}
return arrCopy;
}
Reviewing the above function, despite the fact that it works fine, I realised there could be some performance improvement. Also using ES6 instead of ES5 is a much better approach. To that end, this is the improved code:
const arrayWithoutFastest = (() => {
const isArray = canBeArray => ('isArray' in Array)
? Array.isArray(canBeArray)
: Object.prototype.toString.call(canBeArray) === '[object Array]';
let mapIncludes = (map, key) => map.has(key);
let objectIncludes = (obj, key) => key in obj;
let includes;
function arrayWithoutFastest(arr, ...thisArgs) {
let withoutValues = isArray(thisArgs[0]) ? thisArgs[0] : thisArgs;
if (typeof Map !== 'undefined') {
withoutValues = withoutValues.reduce((map, value) => map.set(value, value), new Map());
includes = mapIncludes;
} else {
withoutValues = withoutValues.reduce((map, value) => { map[value] = value; return map; } , {});
includes = objectIncludes;
}
const arrCopy = [];
const length = arr.length;
for (let i = 0; i < length; i++) {
// If value is not in exclude list
if (!includes(withoutValues, arr[i])) {
arrCopy.push(arr[i]);
}
}
return arrCopy;
}
return arrayWithoutFastest;
})();
How to use:
const arr = [1,2,3,4,5,"name", false];
arrayWithoutFastest(arr, 1); // will return array [2,3,4,5,"name", false]
arrayWithoutFastest(arr, 'name'); // will return [2,3,4,5, false]
arrayWithoutFastest(arr, false); // will return [2,3,4,5]
arrayWithoutFastest(arr,[1,2]); // will return [3,4,5,"name", false];
arrayWithoutFastest(arr, {bar: "foo"}); // will return the same array (new copy)
I am currently writing a blog post in which I have benchmarked several solutions for Array without problem and compared the time it takes to run. I will update this answer with the link once I finish that post. Just to let you know, I have compared the above against lodash's without and in case the browser supports Map
, it beats lodash! Notice that I am not using Array.prototype.indexOf
or Array.prototype.includes
as wrapping the exlcudeValues in a Map
or Object
makes querying faster!
let removeAnElement = (arr, element)=>{
let findIndex = -1;
for (let i = 0; i<(arr.length); i++){
if(arr[i] === element){
findIndex = i;
break;
}
}
if(findIndex == -1){
return arr;
}
for (let i = findIndex; i<(arr.length-1); i++){
arr[i] = arr[i+1];
}
arr.length -= 1;
return arr;
}
let array = ['apple', 'ball', 'cat', 'dog', 'egg'];
let removeElement = 'ball';
let tempArr2 = removeAnElement(array, 'dummy');
console.log(tempArr2);
// ['apple', 'cat', 'dog', 'egg']
let tempArr = removeAnElement(array, removeElement);
console.log(tempArr);`enter code here`
// ['apple', 'cat', 'dog', 'egg']
Using .indexOf() and .splice() - Mutable Pattern
There are two scenarios here:
const drinks = [ 'Tea', 'Coffee', 'Milk'];
const id = 1;
const removedDrink = drinks.splice(id, 1);
console.log(removedDrink)
const drinks = ['Tea','Coffee', 'Milk'];
const id = drinks.indexOf('Coffee'); // 1
const removedDrink = drinks.splice(id, 1);
// ["Coffee"]
console.log(removedDrink);
// ["Tea", "Milk"]
console.log(drinks);
Using .filter() - Immutable Pattern
The best way you can think about this is - instead of “removing” the item, you’ll be “creating” a new array that just does not include that item. So we must find it, and omit it entirely.
const drinks = ['Tea','Coffee', 'Milk'];
const id = 'Coffee';
const idx = drinks.indexOf(id);
const removedDrink = drinks[idx];
const filteredDrinks = drinks.filter((drink, index) => drink == removedDrink);
console.log("Filtered Drinks Array:"+ filteredDrinks);
console.log("Original Drinks Array:"+ drinks);
There are multiple ways to do it, and it’s up to you how you want it to act.
One approach is to use the splice
method and remove the item from the array:
let array = [1, 2, 3]
array.splice(1, 1);
console.log(array)
// return [1, 3]
But make sure you pass the second argument or you end up deleting the whole array after the index.
The second approach is to use the filter
method and the benefit with it is that it is immutable which means your main array doesn't get manipulated:
const array = [1, 2, 3];
const newArray = array.filter(item => item !== 2)
console.log(newArray)
// return [1, 3]
Underscore.js can be used to solve issues with multiple browsers. It uses in-build browser methods if present. If they are absent like in the case of older Internet Explorer versions it uses its own custom methods.
A simple example to remove elements from array (from the website):
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
For removing only the first 34
from ages, not all the ages 34
:
ages.splice(ages.indexOf(34), 1);
Or you can define a method globally:
function remove(array, item){
let ind = array.indexOf(item);
if(ind !== -1)
array.splice(ind, 1);
}
For removing all the ages 34
:
ages = ages.filter(a => a !== 34);
If you want a [...].remove(el)-like syntax, like other programming languages, then you can add this code:
// Add remove method to Array prototype
Array.prototype.remove = function(value, count=this.length) {
while(count > 0 && this.includes(value)) {
this.splice(this.indexOf(value), 1);
count--;
}
return this;
}
// Original array
const arr = [1,2,2,3,2,5,6,7];
// Remove all 2s from array
arr.remove(2); // [1,3,5,6,7]
// Remove one 2 from beginning of array
arr.remove(2, 1); // [1,2,3,2,5,6,7]
// Remove two 2s from beginning of array
arr.remove(2, 2); // [1,3,2,5,6,7]
You can manipulate the method as per your need.
You can simply add remove function to array protoType
something like this :
Array.prototype.remove = function(value) {
return this.filter(item => item !== value)
}
Array.prototype.remove = function(value) {
return this.filter(item => item !== value)
}
let array = [10,15,20]
result = array.remove(10)
console.log(result)
Remove by Index
A function that returns a copy of array without the element at index:
/**
* removeByIndex
* @param {Array} array
* @param {Number} index
*/
function removeByIndex(array, index){
return array.filter(function(elem, _index){
return index != _index;
});
}
l = [1,3,4,5,6,7];
console.log(removeByIndex(l, 1));
$> [ 1, 4, 5, 6, 7 ]
Remove by Value
Function that return a copy of array without the Value.
/**
* removeByValue
* @param {Array} array
* @param {Number} value
*/
function removeByValue(array, value){
return array.filter(function(elem, _index){
return value != elem;
});
}
l = [1,3,4,5,6,7];
console.log(removeByValue(l, 5));
$> [ 1, 3, 4, 6, 7]
You can use lodash _.pull (mutate array), _.pullAt (mutate array) or _.without (does't mutate array),
var array1 = ['a', 'b', 'c', 'd']
_.pull(array1, 'c')
console.log(array1) // ['a', 'b', 'd']
var array2 = ['e', 'f', 'g', 'h']
_.pullAt(array2, 0)
console.log(array2) // ['f', 'g', 'h']
var array3 = ['i', 'j', 'k', 'l']
var newArray = _.without(array3, 'i') // ['j', 'k', 'l']
console.log(array3) // ['i', 'j', 'k', 'l']
I have another good solution for removing from an array:
var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
By my solution you can remove one or more than one item in an array thanks to pure JavaScript. There is no need for another JavaScript library.
var myArray = [1,2,3,4,5]; // First array
var removeItem = function(array,value) { // My clear function
if(Array.isArray(value)) { // For multi remove
for(var i = array.length - 1; i >= 0; i--) {
for(var j = value.length - 1; j >= 0; j--) {
if(array[i] === value[j]) {
array.splice(i, 1);
};
}
}
}
else { // For single remove
for(var i = array.length - 1; i >= 0; i--) {
if(array[i] === value) {
array.splice(i, 1);
}
}
}
}
removeItem(myArray,[1,4]); // myArray will be [2,3,5]
You have 1 to 9 in the array, and you want remove 5. Use the below code:
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var newNumberArray = numberArray.filter(m => {
return m !== 5;
});
console.log("new Array, 5 removed", newNumberArray);
If you want to multiple values. Example:- 1,7,8
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var newNumberArray = numberArray.filter(m => {
return (m !== 1) && (m !== 7) && (m !== 8);
});
console.log("new Array, 1,7 and 8 removed", newNumberArray);
If you want to remove an array value in an array. Example: [3,4,5]
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var removebleArray = [3,4,5];
var newNumberArray = numberArray.filter(m => {
return !removebleArray.includes(m);
});
console.log("new Array, [3,4,5] removed", newNumberArray);
Includes supported browser is link.
This post summarizes common approaches to element removal from an array as of ECMAScript 2019 (ES10).
.splice()
| In-place: Yes |
| Removes duplicates: Yes(loop), No(indexOf) |
| By value / index: By index |
If you know the value you want to remove from an array you can use the splice method. First, you must identify the index of the target item. You then use the index as the start element and remove just one element.
// With a 'for' loop
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
for( let i = 0; i < arr.length; i++){
if ( arr[i] === 5) {
arr.splice(i, 1);
}
} // => [1, 2, 3, 4, 6, 7, 8, 9, 0]
// With the .indexOf() method
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const i = arr.indexOf(5);
arr.splice(i, 1); // => [1, 2, 3, 4, 6, 7, 8, 9, 0]
.filter()
method| In-place: No |
| Removes duplicates: Yes |
| By value / index: By value |
The specific element can be filtered out from the array, by providing a filtering function. Such function is then called for every element in the array.
const value = 3
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => item !== value)
console.log(arr)
// [ 1, 2, 4, 5 ]
Array.prototype
| In-place: Yes/No (Depends on implementation) |
| Removes duplicates: Yes/No (Depends on implementation) |
| By value / index: By index / By value (Depends on implementation) |
The prototype of Array can be extended with additional methods. Such methods will be then available to use on created arrays.
Note: Extending prototypes of objects from the standard library of JavaScript (like Array) is considered by some as an antipattern.
// In-place, removes all, by value implementation
Array.prototype.remove = function(item) {
for (let i = 0; i < this.length; i++) {
if (this[i] === item) {
this.splice(i, 1);
}
}
}
const arr1 = [1,2,3,1];
arr1.remove(1) // arr1 equals [2,3]
// Non-stationary, removes first, by value implementation
Array.prototype.remove = function(item) {
const arr = this.slice();
for (let i = 0; i < this.length; i++) {
if (arr[i] === item) {
arr.splice(i, 1);
return arr;
}
}
return arr;
}
let arr2 = [1,2,3,1];
arr2 = arr2.remove(1) // arr2 equals [2,3,1]
delete
operator| In-place: Yes |
| Removes duplicates: No |
| By value / index: By index |
Using the delete operator does not affect the length property. Nor does it affect the indexes of subsequent elements. The array becomes sparse, which is a fancy way of saying the deleted item is not removed but becomes undefined.
const arr = [1, 2, 3, 4, 5, 6];
delete arr[4]; // Delete element with index 4
console.log( arr ); // [1, 2, 3, 4, undefined, 6]
The delete operator is designed to remove properties from JavaScript objects, which arrays are objects.
Object
utilities (>= ES10)| In-place: No |
| Removes duplicates: Yes |
| By value / index: By value |
ES10 introduced Object.fromEntries
, which can be used to create the desired Array from any Array-like object and filter unwanted elements during the process.
const object = [1,2,3,4];
const valueToRemove = 3;
const arr = Object.values(Object.fromEntries(
Object.entries(object)
.filter(([ key, val ]) => val !== valueToRemove)
));
console.log(arr); // [1,2,4]
length
| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |
JavaScript Array elements can be removed from the end of an array by setting the length property to a value less than the current value. Any element whose index is greater than or equal to the new length will be removed.
const arr = [1, 2, 3, 4, 5, 6];
arr.length = 5; // Set length to remove element
console.log( arr ); // [1, 2, 3, 4, 5]
.pop()
method| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |
The pop method removes the last element of the array, returns that element, and updates the length property. The pop method modifies the array on which it is invoked, This means unlike using delete the last element is removed completely and the array length reduced.
const arr = [1, 2, 3, 4, 5, 6];
arr.pop(); // returns 6
console.log( arr ); // [1, 2, 3, 4, 5]
| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |
The .shift()
method works much like the pop method except it removes the first element of a JavaScript array instead of the last. When the element is removed the remaining elements are shifted down.
const arr = [1, 2, 3, 4];
arr.shift(); // returns 1
console.log( arr ); // [2, 3, 4]
| In-place: Yes |
| Removes duplicates: N/A |
| By value / index: N/A |
The fastest technique is to set an array variable to an empty array.
let arr = [1];
arr = []; //empty array
Alternatively technique from 2.1.1 can be used by setting length to 0.
Array.prototype.removeByValue = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
var fruits = ['apple', 'banana', 'carrot', 'orange'];
fruits.removeByValue('banana');
console.log(fruits);
// -> ['apple', 'carrot', 'orange']
I don't know how you are expecting array.remove(int)
to behave. There are three possibilities I can think of that you might want.
To remove an element of an array at an index i
:
array.splice(i, 1);
If you want to remove every element with value number
from the array:
for (var i = array.length - 1; i >= 0; i--) {
if (array[i] === number) {
array.splice(i, 1);
}
}
If you just want to make the element at index i
no longer exist, but you don't want the indexes of the other elements to change:
delete array[i];
It depends on whether you want to keep an empty spot or not.
If you do want an empty slot:
array[index] = undefined;
If you don't want an empty slot:
//To keep the original:
//oldArray = [...array];
//This modifies the array.
array.splice(index, 1);
And if you need the value of that item, you can just store the returned array's element:
var value = array.splice(index, 1)[0];
If you want to remove at either end of the array, you can use array.pop()
for the last one or array.shift()
for the first one (both return the value of the item as well).
If you don't know the index of the item, you can use array.indexOf(item)
to get it (in a if()
to get one item or in a while()
to get all of them). array.indexOf(item)
returns either the index or -1
if not found.
There are already a lot of answers, but because no one has done it with a one liner yet, I figured I'd show my method. It takes advantage of the fact that the string.split() function will remove all of the specified characters when creating an array. Here is an example:
var ary = [1,2,3,4,1234,10,4,5,7,3];
out = ary.join("-").split("-4-").join("-").split("-");
console.log(out);
In this example, all of the 4's are being removed from the array ary. However, it is important to note that any array containing the character "-" will cause issues with this example. In short, it will cause the join("-") function to piece your string together improperly. In such a situation, all of the the "-" strings in the above snipet can be replaced with any string that will not be used in the original array. Here is another example:
var ary = [1,2,3,4,'-',1234,10,'-',4,5,7,3];
out = ary.join("!@#").split("!@#4!@#").join("!@#").split("!@#");
console.log(out);
I post my code that removes an array element in place, and reduce the array length as well.
function removeElement(idx, arr) {
// Check the index value
if (idx < 0 || idx >= arr.length) {
return;
}
// Shift the elements
for (var i = idx; i > 0; --i) {
arr[i] = arr[i - 1];
}
// Remove the first element in array
arr.shift();
}
Today (2019-12-09) I conduct performance tests on macOS v10.13.6 (High Sierra) for chosen solutions. I show delete
(A), but I do not use it in comparison with other methods, because it left empty space in the array.
The conclusions
array.splice
(C) (except Safari for small arrays where it has the second time)array.slice+splice
(H) is the fastest immutable solution for Firefox and Safari; Array.from
(B) is fastest in ChromeIn tests, I remove the middle element from the array in different ways. The A, C solutions are in-place. The B, D, E, F, G, H solutions are immutable.
Results for an array with 10 elements
In Chrome the array.splice
(C) is the fastest in-place solution. The array.filter
(D) is the fastest immutable solution. The slowest is array.slice
(F). You can perform the test on your machine here.
Results for an array with 1.000.000 elements
In Chrome the array.splice
(C) is the fastest in-place solution (the delete
(C) is similar fast - but it left an empty slot in the array (so it does not perform a 'full remove')). The array.slice-splice
(H) is the fastest immutable solution. The slowest is array.filter
(D and E). You can perform the test on your machine here.
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var log = (letter,array) => console.log(letter, array.join `,`);
function A(array) {
var index = array.indexOf(5);
delete array[index];
log('A', array);
}
function B(array) {
var index = array.indexOf(5);
var arr = Array.from(array);
arr.splice(index, 1)
log('B', arr);
}
function C(array) {
var index = array.indexOf(5);
array.splice(index, 1);
log('C', array);
}
function D(array) {
var arr = array.filter(item => item !== 5)
log('D', arr);
}
function E(array) {
var index = array.indexOf(5);
var arr = array.filter((item, i) => i !== index)
log('E', arr);
}
function F(array) {
var index = array.indexOf(5);
var arr = array.slice(0, index).concat(array.slice(index + 1))
log('F', arr);
}
function G(array) {
var index = array.indexOf(5);
var arr = [...array.slice(0, index), ...array.slice(index + 1)]
log('G', arr);
}
function H(array) {
var index = array.indexOf(5);
var arr = array.slice(0);
arr.splice(index, 1);
log('H', arr);
}
A([...a]);
B([...a]);
C([...a]);
D([...a]);
E([...a]);
F([...a]);
G([...a]);
H([...a]);
This snippet only presents code used in performance tests - it does not perform tests itself.
Comparison for browsers: Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0
Remove a specific element from an array can be done in one line with the filter option, and it's supported by all browsers: https://caniuse.com/#search=filter%20array
function removeValueFromArray(array, value) {
return array.filter(e => e != value)
}
I tested this function here: https://bit.dev/joshk/jotils/remove-value-from-array/~code#test.ts
You can use splice
to remove objects or values from an array.
Let's consider an array of length 5
, with values 10
,20
,30
,40
,50
, and I want to remove the value 30
from it.
var array = [10,20,30,40,50];
if (array.indexOf(30) > -1) {
array.splice(array.indexOf(30), 1);
}
console.log(array); // [10,20,40,50]
You can create a prototype for that. Just pass the array element and the value which you want to remove from the array element:
Array.prototype.removeItem = function(array,val) {
array.forEach((arrayItem,index) => {
if (arrayItem == val) {
array.splice(index, 1);
}
});
return array;
}
var DummyArray = [1, 2, 3, 4, 5, 6];
console.log(DummyArray.removeItem(DummyArray, 3));
You can add a prototype function to "remove" the element from the array.
The following example shows how to simply remove an element from an array, when we know the index of the element. We use it in the Array.filter
method.
Array.prototype.removeByIndex = function(i) {
if(!Number.isInteger(i) || i < 0) {
// i must be an integer
return this;
}
return this.filter((f, indx) => indx !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];
var b = a.removeByIndex(2);
console.log(a);
console.log(b);
Sometimes we don't know the index of the element.
Array.prototype.remove = function(i) {
return this.filter(f => f !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];
var b = a.remove(5).remove(null);
console.log(a);
console.log(b);
// It removes all occurrences of searched value
But, when we want to remove only the first occurrence of the searched value, we can use the Array.indexOf
method in our function.
Array.prototype.removeFirst = function(i) {
i = this.indexOf(i);
if(!Number.isInteger(i) || i < 0) {
return this;
}
return this.filter((f, indx) => indx !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];
var b = a.removeFirst(5).removeFirst(null);
console.log(a);
console.log(b);
(function removeFromArrayPolyfill() {
if (window.Array.prototype.remove) return;
Array.prototype.remove = function (value) {
if (!this.length || !value) return;
const indexOfValue = this.indexOf(value);
if (indexOfValue >= 0) {
this.splice(indexOfValue, 1);
}
};
})();
// testing polyfill
const nums = [10, 20, 30];
nums.remove(20);
console.log(nums);//[10,30]
You should never mutate your array as this is against the functional programming pattern. You can create a new array without referencing the one you want to change data of using the ECMAScript 6 method filter
;
var myArray = [1, 2, 3, 4, 5, 6];
Suppose you want to remove 5
from the array, you can simply do it like this:
myArray = myArray.filter(value => value !== 5);
This will give you a new array without the value you wanted to remove. So the result will be:
[1, 2, 3, 4, 6]; // 5 has been removed from this array
For further understanding you can read the MDN documentation on Array.filter.
filter is an elegant way of achieving it without mutating the original array
const num = 3;
let arr = [1, 2, 3, 4];
const arr2 = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 3, 4]
console.log(arr2); // [1, 2, 4]
You can use filter
and then assign the result to the original array if you want to achieve a mutation removal behaviour.
const num = 3;
let arr = [1, 2, 3, 4];
arr = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 4]
By the way, filter
will remove all of the occurrences matched in the condition (not just the first occurrence) like you can see in the following example
const num = 3;
let arr = [1, 2, 3, 3, 3, 4];
arr = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 4]
In case, you just want to remove the first occurrence, you can use the splice method
const num = 3;
let arr = [1, 2, 3, 3, 3, 4];
const idx = arr.indexOf(num);
arr.splice(idx, idx !== -1 ? 1 : 0);
console.log(arr); // [1, 2, 3, 3, 4]
There are many ways to remove a specific element from a JavaScript array. The following are the 5 best available methods I could came up with in my research.
1. Using 'splice()' method directly
In the following code segment, elements in a specific pre-determined location is/are removed from the array.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log("Original array: " + arr);
var removed = arr.splice(4, 2);
console.log("Modified array: " + arr);
console.log("Elements removed: " + removed);
2. Remove elements by 'value' using 'splice()' method
In the following code segment we can remove all the elements equal to a pre-determined value (ex: all the elements equal to value 6) using a if condition inside a for loop.
var arr = [1, 2, 6, 3, 2, 6, 7, 8, 9, 10];
console.log("Original array: " + arr);
for (var i = 0; i < arr.length; i++) {
if (arr[i] === 6) {
var removed = arr.splice(i, 1);
i--;
}
}
console.log("Modified array: " + arr); // 6 is removed
console.log("Removed elements: " + removed);
3. Using the 'filter()' method remove elements selected by value
Similar to the implementation using 'splice()' method, but instead of mutating the existing array, it create a new array of elements having removed the unwanted element.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var filtered = array.filter(function(value, index, arr) {
return value != 6 ;
});
console.log("Original array: "+array);
console.log("New array created: "+filtered); // 6 is removed
4. Using the 'remove()' method in 'Lodash' JavaScript library
In the following code segment, there remove() method in the JavaScript library called 'Lodash'. This method is also similar to the filter method.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log("Original array: " + array);
var removeElement = _.remove(array, function(n) {
return n === 6;
});
console.log("Modified array: " + array);
console.log("Removed elements: " + removeElement); // 6 is removed
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
5. making a custom remove method
There is no native 'array.remove' method in JavaScript, but we can create one using above methods we used as implemented in the following code snippet.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function arrayRemove(arr, value) {
return arr.filter(function(element) {
return element != value;
});
}
console.log("Original array: " + array);
console.log("Modified array: " + arrayRemove(array, 6)); // 6 is removed
The final method (number 5) is more appropriate for solving the above issue.
To me the simpler is the better, and as we are in 2018 (near 2019) I give you this (near) one-liner to answer the original question:
Array.prototype.remove = function (value) {
return this.filter(f => f != value)
}
The useful thing is that you can use it in a curry expression such as:
[1,2,3].remove(2).sort()
I think many of the JavaScript instructions are not well thought out for functional programming. Splice returns the deleted element where most of the time you need the reduced array. This is bad.
Imagine you are doing a recursive call and have to pass an array with one less item, probably without the current indexed item. Or imagine you are doing another recursive call and has to pass an array with an element pushed.
In neither of these cases you can do myRecursiveFunction(myArr.push(c))
or myRecursiveFunction(myArr.splice(i,1))
. The first idiot will in fact pass the length of the array and the second idiot will pass the deleted element as a parameter.
So what I do in fact... For deleting an array element and passing the resulting to a function as a parameter at the same time I do as follows
myRecursiveFunction(myArr.slice(0,i).concat(a.slice(i+1)))
When it comes to push that's more silly... I do like,
myRecursiveFunction((myArr.push(c),myArr))
I believe in a proper functional language a method mutating the object it's called upon must return a reference to the very object as a result.
There are many fantastic answers here, but for me, what worked most simply wasn't removing my element from the array completely, but simply setting the value of it to null.
This works for most cases I have and is a good solution since I will be using the variable later and don't want it gone, just empty for now. Also, this approach is completely cross-browser compatible.
array.key = null;
You could use the standard __proto__
of JavaScript and define this function. For example,
let data = [];
data.__proto__.remove = (n) => { data = data.flatMap((v) => { return v !== n ? v : []; }) };
data = [1, 2, 3];
data.remove(2);
console.log(data); // [1,3]
data = ['a','b','c'];
data.remove('b');
console.log(data); // [a,c]
Using filter(): The filter() method creates a new array with all elements that pass a certain condition.
You can use it to filter out the specific item you want to remove. Here's an example:
const array = [1, 2, 3, 4, 5];
const itemToRemove = 3;
const filteredArray = array.filter(item => item !== itemToRemove);
console.log(filteredArray);
// Output: [1, 2, 4, 5]
If you want to create a new array instead of modifying the original array in place, use Array.prototype.toSpliced()
:
const index = array.indexOf(value);
const newArray = array.toSpliced(index, 1);
I made these methods as extension methods for Array-type objects, you can add them to your codes and use them like native Array methods.
if (!Array.prototype.removeItem) {
Object.defineProperty(Array.prototype, 'removeItem', {
/**
* Removing first instance of specified item by @value from array
* @param {any} value
* @returns
*/
value: function (value) {
var index = this.indexOf(value);
if (index > -1)
this.splice(index, 1);
return this;
}
});
}
if (!Array.prototype.removeIndex) {
Object.defineProperty(Array.prototype, 'removeIndex', {
/**
* Removing item at @index
* @param {int} index
* @returns
*/
value: function (index) {
if (index > -1)
this.splice(index, 1);
return this;
}
});
}
if (!Array.prototype.removeItems) {
Object.defineProperty(Array.prototype, 'removeItems', {
/**
* Removing all items like @value .\n
* If @value is null this function will removes all items
* @param {any} value
* @returns
*/
value: function (value) {
if (value == null)
return [];
else {
let i = 0;
while (i < this.length) {
if (this[i] === value)
this.splice(i, 1);
else
++i;
}
}
return this;
}
});
}
I found another way to remove specific item from array
In the below example, I am removing "2" from the list.
1. If Array contains duplicate values, e.g., [1,2,3,4,2,2,1,1,2]
var arr = [1,2,3,4,2,2,1,1,2];
console.log(arr.filter((e)=>e!=2));
2. If Array doesn't contain duplicate value eg. [1,2,3,4,5]
var arr = [1,2,3,4];
arr.splice(arr.indexOf(2),1);
console.log(arr);
If you want to avoid modifying the original array directly, use Array.prototype.toSpliced()
.
Nevertheless, please be mindful of its limited browser support at present.
const stocks = ["Microsoft", "Nvidia", "Amazon"]
const copy = stocks.toSpliced(0, 1, "Alphabet")
console.log("Copy", copy)
console.log("Original", stocks)
There are two main scenarios:
let array = ['a', 'b', 'c', 'd', 'c', 'e', 'f', 'g'];
array = array.filter((item, ind) => (ind != array.indexOf('c')));
console.log(array);
We simply find the index of c and filter that out. Of course, in order to speed things up, we could compute .indexOf
just before the .filter()
call.
let array = ['a', 'b', 'c', 'd', 'c', 'e', 'f', 'g'];
array = array.filter(item => (item !== 'c'));
console.log(array);
You can extend the array object to define a custom delete function as follows:
let numbers = [1,2,4,4,5,3,45,9];
numbers.delete = function(value){
var indexOfTarget = this.indexOf(value)
if(indexOfTarget !== -1)
{
console.log("array before delete " + this)
this.splice(indexOfTarget, 1)
console.log("array after delete " + this)
}
else{
console.error("element " + value + " not found")
}
}
numbers.delete(888)
// Expected output:
// element 888 not found
numbers.delete(1)
// Expected output;
// array before delete 1,2,4,4,5,3,45,9
// array after delete 2,4,4,5,3,45,9
function removeSingle(array, element) {
const index = array.indexOf(element)
if (index >= 0) {
array.splice(index, 1)
}
}
This is more complicated to ensure the algorithm runs in O(N) time.
function removeAll(array, element) {
let newLength = 0
for (const elem of array) {
if (elem !== number) {
array[newLength++] = elem
}
}
array.length = newLength
}
array.filter(elem => elem !== number)
var index,
input = [1,2,3],
indexToRemove = 1;
integers = [];
for (index in input) {
if (input.hasOwnProperty(index)) {
if (index !== indexToRemove) {
integers.push(result);
}
}
}
input = integers;
This solution will take an array of input and will search through the input for the value to remove. This will loop through the entire input array and the result will be a second array integers that has had the specific index removed. The integers array is then copied back into the input array.
You can do it easily with the filter method:
function remove(arrOriginal, elementToRemove){
return arrOriginal.filter(function(el){return el !== elementToRemove});
}
console.log(remove([1, 2, 1, 0, 3, 1, 4], 1));
This removes all elements from the array and also works faster than a combination of slice
and indexOf
.
I know there are a lot of answers already, but many of them seem to over complicate the problem. Here is a simple, recursive way of removing all instances of a key - calls self until index isn't found. Yes, it only works in browsers with indexOf
, but it's simple and can be easily polyfilled.
Stand-alone function
function removeAll(array, key){
var index = array.indexOf(key);
if(index === -1) return;
array.splice(index, 1);
removeAll(array,key);
}
Prototype method
Array.prototype.removeAll = function(key){
var index = this.indexOf(key);
if(index === -1) return;
this.splice(index, 1);
this.removeAll(key);
}
It depends on whether you want to keep an empty spot or not.
If you do want an empty slot:
array[index] = undefined;
If you don't want an empty slot:
To keep the original:
oldArray = [...array];
This modifies the array.
array.splice(index, 1);
And if you need the value of that item, you can just store the returned array's element:
var value = array.splice(index, 1)[0];
If you want to remove at either end of the array, you can use array.pop() for the last one or array.shift() for the first one (both return the value of the item as well).
If you don't know the index of the item, you can use array.indexOf(item) to get it (in a if() to get one item or in a while() to get all of them).
array.indexOf(item)
returns either the index or -1 if not found.
let a1 = {name:'a1'}
let a2 = {name:'a2'}
let a3 = {name:'a3'}
let list = [a1, a2, a3]
_.remove(list, a2)
//list now is [{name: "a1"}, {name: "a3"}]
Check this for details: .remove(array, [predicate=.identity])
Update: This method is recommended only if you cannot use ECMAScript 2015 (formerly known as ES6). If you can use it, other answers here provide much neater implementations.
This gist here will solve your problem, and also deletes all occurrences of the argument instead of just 1 (or a specified value).
Array.prototype.destroy = function(obj){
// Return null if no objects were found and removed
var destroyed = null;
for(var i = 0; i < this.length; i++){
// Use while-loop to find adjacent equal objects
while(this[i] === obj){
// Remove this[i] and store it within destroyed
destroyed = this.splice(i, 1)[0];
}
}
return destroyed;
}
Usage:
var x = [1, 2, 3, 3, true, false, undefined, false];
x.destroy(3); // => 3
x.destroy(false); // => false
x; // => [1, 2, true, undefined]
x.destroy(true); // => true
x.destroy(undefined); // => undefined
x; // => [1, 2]
x.destroy(3); // => null
x; // => [1, 2]
I like this one-liner:
arr.includes(val) && arr.splice(arr.indexOf(val), 1)
null
or undefined
As a prototype
// remove by value. return true if value found and removed, false otherwise
Array.prototype.remove = function(val)
{
return this.includes(val) && !!this.splice(this.indexOf(val), 1);
}
(Yes, I read all other answers and couldn't find one that combines includes
and splice
in the same line.)
I tested splice
and filter
to see which is faster:
let someArr = [...Array(99999).keys()]
console.time('filter')
someArr.filter(x => x !== 6666)
console.timeEnd('filter')
console.time('splice by indexOf')
someArr.splice(someArr.indexOf(6666), 1)
console.timeEnd('splice by indexOf')
On my machine, splice
is faster. This makes sense, as splice
merely edits an existing array, whereas filter
creates a new array.
That said, filter
is logically cleaner (easier to read) and fits better into a coding style that uses immutable state. So it's up to you whether you want to make that trade-off.
EDIT:
To be clear, splice
and filter
do different things: splice
edits an array, whereas filter
creates a new one. But either can be used to obtain an array with a given element removed.
If you have complex objects in the array you can use filters?
In situations where $.inArray
or array.splice
is not as easy to use. Especially if the objects are perhaps shallow in the array.
E.g. if you have an object with an id field and you want the object removed from an array:
this.array = this.array.filter(function(element, i) {
return element.id !== idToRemove;
});
Delete an element from last
arrName.pop();
Delete an element from first
arrName.shift();
Delete from the middle
arrName.splice(starting index, number of element you wnt to delete);
Example: arrName.splice(1, 1);
Delete one element from last
arrName.splice(-1);
Delete by using an array index number
delete arrName[1];
Your question did not indicate if order or distinct values are a requirement.
If you don't care about order, and will not have the same value in the container more than once, use a Set. It will be way faster, and more succinct.
var aSet = new Set();
aSet.add(1);
aSet.add(2);
aSet.add(3);
aSet.delete(2);
Here are a few ways to remove an item from an array using JavaScript.
All the method described do not mutate the original array, and instead create a new one.
Suppose you have an array, and you want to remove an item in position i
.
One method is to use slice()
:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 3
const filteredItems = items.slice(0, i).concat(items.slice(i+1, items.length))
console.log(filteredItems)
slice()
creates a new array with the indexes it receives. We simply create a new array, from start to the index we want to remove, and concatenate another array from the first position following the one we removed to the end of the array.
In this case, one good option is to use filter()
, which offers a more declarative approach:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)
console.log(filteredItems)
This uses the ES6 arrow functions. You can use the traditional functions to support older browsers:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(function(item) {
return item !== valueToRemove
})
console.log(filteredItems)
or you can use Babel and transpile the ES6 code back to ES5 to make it more digestible to old browsers, yet write modern JavaScript in your code.
What if instead of a single item, you want to remove many items?
Let's find the simplest solution.
You can just create a function and remove items in series:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const removeItem = (items, i) =>
items.slice(0, i-1).concat(items.slice(i, items.length))
let filteredItems = removeItem(items, 3)
filteredItems = removeItem(filteredItems, 5)
//["a", "b", "c", "d"]
console.log(filteredItems)
You can search for inclusion inside the callback function:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valuesToRemove = ['c', 'd']
const filteredItems = items.filter(item => !valuesToRemove.includes(item))
// ["a", "b", "e", "f"]
console.log(filteredItems)
splice()
(not to be confused with slice()
) mutates the original array, and should be avoided.
(originally posted on my site https://flaviocopes.com/how-to-remove-item-from-array/)
Define a method named remove() on array objects using the prototyping feature of JavaScript.
Use splice() method to fulfill your requirement.
Please have a look at the below code.
Array.prototype.remove = function(item) {
// 'index' will have -1 if 'item' does not exist,
// else it will have the index of the first item found in the array
var index = this.indexOf(item);
if (index > -1) {
// The splice() method is used to add/remove items(s) in the array
this.splice(index, 1);
}
return index;
}
var arr = [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];
// Printing array
// [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];
console.log(arr)
// Removing 67 (getting its index, i.e. 2)
console.log("Removing 67")
var index = arr.remove(67)
if (index > 0){
console.log("Item 67 found at ", index)
} else {
console.log("Item 67 does not exist in array")
}
// Printing updated array
// [ 11, 22, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];
console.log(arr)
// ............... Output ................................
// [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4 ]
// Removing 67
// Item 67 found at 2
// [ 11, 22, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4 ]
Note: The below is the full example code executed on the Node.js REPL which describes the use of push(), pop(), shift(), unshift(), and splice() methods.
> // Defining an array
undefined
> var arr = [12, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34];
undefined
> // Getting length of array
undefined
> arr.length;
16
> // Adding 1 more item at the end i.e. pushing an item
undefined
> arr.push(55);
17
> arr
[ 12, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34, 55 ]
> // Popping item from array (i.e. from end)
undefined
> arr.pop()
55
> arr
[ 12, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> // Remove item from beginning
undefined
> arr.shift()
12
> arr
[ 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> // Add item(s) at beginning
undefined
> arr.unshift(67); // Add 67 at beginning of the array and return number of items in updated/new array
16
> arr
[ 67, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> arr.unshift(11, 22); // Adding 2 more items at the beginning of array
18
> arr
[ 11, 22, 67, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> // Define a method on array (temporarily) to remove an item and return the index of removed item; if it is found else return -1
undefined
> Array.prototype.remove = function(item) {
... var index = this.indexOf(item);
... if (index > -1) {
..... this.splice(index, 1); // splice() method is used to add/remove items in array
..... }
... return index;
... }
[Function]
>
> arr
[ 11, 22, 67, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(45); // Remove 45 (you will get the index of removed item)
3
> arr
[ 11, 22, 67, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(22) // Remove 22
1
> arr
[ 11, 67, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> arr.remove(67) // Remove 67
1
> arr
[ 11, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(89) // Remove 89
2
> arr
[ 11, 67, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(100); // 100 doesn't exist, remove() will return -1
-1
>
An immutable way of removing an element from an array using the ES6 spread operator.
Let's say you want to remove 4.
let array = [1,2,3,4,5]
const index = array.indexOf(4)
let new_array = [...array.slice(0,index), ...array.slice(index+1, array.length)]
console.log(new_array)
=> [1, 2, 3, 5]
In JavaScript, you can use the Array.prototype.filter()
method to remove a specific value from an array.
Here's an example:
let array = [1, 2, 3, 4, 5];
let value = 3;
array = array.filter(function(element) {
return element !== value;
});
console.log(array); // Output: [1, 2, 4, 5]
In the above code, we first create an array and define the value that we want to remove. Then we use the filter()
method to create a new array that includes only the elements that are not equal to the given value. Finally, we assign the new array back to the original array variable.
Note that the filter()
method creates a new array instead of modifying the original array. If you want to modify the original array directly, you can use a for loop to iterate over the array and remove the element at the given index.
Here's an example:
let array = [1, 2, 3, 4, 5];
let value = 3;
for (let i = 0; i < array.length; i++) {
if (array[i] === value) {
array.splice(i, 1);
i--; // decrement i since the array has been modified
}
}
console.log(array); // Output: [1, 2, 4, 5]
In this example, we use a for loop
to iterate over the array and check if each element is equal to the given value. If it is, we use the splice() method to remove the element at the current index. Since the splice()
method modifies the original array, we decrement i
to ensure that we check the next element in the updated array.
I would like to club every possible solutions and rank it based on the performance. The one placed on top is more preferred to use than the last ones.
Consider this base case for all the methods:
let arr = [1, 2, 3, 4, 5];
let elementToRemove = 4;
let indexToRemove = arr.indexOf(elementToRemove);
splice()
method: [Best Approach / Efficient]// When you don't know index
arr.splice(indexToRemove,1); // Remove a item at index of elementToRemove
// When you know index
arr.splice(3, 1); // Remove one item at index 3
console.log(arr); // Output: [1, 2, 3, 5]
filter()
method: [Good Approach]let filteredArr = arr.filter((num) => num !== elementToRemove);
console.log(filteredArr); // Output: [1, 2, 3, 5]
slice()
method: [Longer Approach(Too much expressions)]let newArr = arr.slice(0, indexToRemove).concat(arr.slice(indexToRemove + 1));
console.log(newArr); // Output: [1, 2, 3, 5]
forEach()
method: [Not recommended as it iterates through every element]let newArr = [];
arr.forEach((num) => {
if(num !== elementToRemove){
newArr.push(num);
}
});
console.log(newArr); // Output: [1, 2, 3, 5]
I had this problem myself (in a situation where replacing the array was acceptable) and solved it with a simple:
var filteredItems = this.items.filter(function (i) {
return i !== item;
});
To give the above snippet a bit of context:
self.thingWithItems = {
items: [],
removeItem: function (item) {
var filteredItems = this.items.filter(function (i) {
return i !== item;
});
this.items = filteredItems;
}
};
This solution should work with both reference and value items. It all depends whether you need to maintain a reference to the original array as to whether this solution is applicable.
Removing a particular element/string from an array can be done in a one-liner:
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
where:
theArray: the array you want to remove something particular from
stringToRemoveFromArray: the string you want to be removed and 1 is the number of elements you want to remove.
NOTE: If "stringToRemoveFromArray" is not located in the array, this will remove the last element of the array.
It's always good practice to check if the element exists in your array first, before removing it.
if (theArray.indexOf("stringToRemoveFromArray") >= 0){
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
}
Depending if you have newer or older version of Ecmascript running on your client's computers:
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
OR
var array = ['1','2','3','4','5','6'];
var newArray = array.filter(function(item){ return item !== '3' });
Where '3' is the value you want to be removed from the array.
The array would then become : ['1','2','4','5','6']
If the array contains duplicate values and you want to remove all the occurrences of your target then this is the way to go...
let data = [2, 5, 9, 2, 8, 5, 9, 5];
let target = 5;
data = data.filter(da => da !== target);
Note: - the filter doesn't change the original array; instead it creates a new array.
So assigning again is important.
That's led to another problem. You can't make the variable const
. It should be let
or var
.
Array.prototype.remove = function(start, end) {
var n = this.slice((end || start) + 1 || this.length);
return this.length = start < 0 ? this.length + start : start,
this.push.apply(this, n)
}
start
and end
can be negative. In that case they count from the end of the array.
If only start
is specified, only one element is removed.
The function returns the new array length.
z = [0,1,2,3,4,5,6,7,8,9];
newlength = z.remove(2,6);
(8) [0, 1, 7, 8, 9]
z=[0,1,2,3,4,5,6,7,8,9];
newlength = z.remove(-4,-2);
(7) [0, 1, 2, 3, 4, 5, 9]
z=[0,1,2,3,4,5,6,7,8,9];
newlength = z.remove(3,-2);
(4) [0, 1, 2, 9]
Try to remove the array element using the delete operator
For an instance:
const arr = [10, 20, 30, 40, 50, 60];
delete arr[2]; // It will Delete element present at index 2
console.log( arr ); // [10, 20, undefined , 40, 50, 60]
Note: Using delete operator will leave empty spaces/ holes in an array. It will not alert the length of an array. To change the length of an array when the element is deleted from it, use splice method instead.
Hope this could resolve all your problems.
The best way to remove an item from an array is to use the filter method.
.filter()
returns a new array without the filtered items.
items = items.filter(e => e.id !== item.id);
This .filter()
method maps to a complete array and when I return the true condition, it pushes that current item to the filtered array.
Read more on filter here.
This function removes an element from an array from a specific position.
array.remove(position);
Array.prototype.remove = function (pos) {
this.splice(pos, 1);
}
var arr = ["a", "b", "c", "d", "e"];
arr.remove(2); // remove "c"
console.log(arr);
If you don't know the location of the item to delete use this:
array.erase(element);
Array.prototype.erase = function(el) {
let p = this.indexOf(el); // indexOf use strict equality (===)
if(p != -1) {
this.splice(p, 1);
}
}
var arr = ["a", "b", "c", "d", "e"];
arr.erase("c");
console.log(arr);
To find and remove a particular string from an array of strings:
var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car"); // Get "car" index
// Remove car from the colors array
colors.splice(carIndex, 1); // colors = ["red", "blue", "green"]
Source: https://www.codegrepper.com/?search_term=remove+a+particular+element+from+array
This provides a predicate instead of a value.
NOTE: it will update the given array, and return the affected rows.
var removed = helper.remove(arr, row => row.id === 5 );
var removed = helper.removeAll(arr, row => row.name.startsWith('BMW'));
var helper = {
// Remove and return the first occurrence
remove: function(array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return array.splice(i, 1);
}
}
},
// Remove and return all occurrences
removeAll: function(array, predicate) {
var removed = [];
for (var i = 0; i < array.length; ) {
if (predicate(array[i])) {
removed.push(array.splice(i, 1));
continue;
}
i++;
}
return removed;
},
};
You can do this task in many ways in JavaScript
If you know the index of the value: in this case you can use splice
var arr = [1,2,3,4]
// Let's say we have the index, coming from some API
let index = 2;
// splice is a destructive method and modifies the original array
arr.splice(2, 1)
If you don't have the index and only have the value: in this case you can use filter
// Let's remove '2', for example
arr = arr.filter((value)=>{
return value !== 2;
})
For example, you have a characters array and want to delete "A" from the array.
The array has a filter method which can filter and return only those elements that you want.
let CharacterArray = ['N', 'B', 'A'];
I want to return elements apart from 'A'.
CharacterArray = CharacterArray.filter(character => character !== 'A');
Then CharacterArray must be: ['N', 'B']
To remove a particular element or subsequent elements, Array.splice() method works well.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements, and it returns the removed item(s).
Syntax: array.splice(index, deleteCount, item1, ....., itemX)
Here index
is mandatory and rest arguments are optional.
For example:
let arr = [1, 2, 3, 4, 5, 6];
arr.splice(2,1);
console.log(arr);
// [1, 2, 4, 5, 6]
Note: Array.splice() method can be used if you know the index of the element which you want to delete. But we may have a few more cases as mentioned below:
In case you want to delete just last element, you can use Array.pop()
In case you want to delete just first element, you can use Array.shift()
If you know the element alone, but not the position (or index) of the element, and want to delete all matching elements using Array.filter() method:
let arr = [1, 2, 1, 3, 4, 1, 5, 1];
let newArr = arr.filter(function(val){
return val !== 1;
});
//newArr => [2, 3, 4, 5]
Or by using the splice() method as:
let arr = [1, 11, 2, 11, 3, 4, 5, 11, 6, 11];
for (let i = 0; i < arr.length-1; i++) {
if ( arr[i] === 11) {
arr.splice(i, 1);
}
}
console.log(arr);
// [1, 2, 3, 4, 5, 6]
Or suppose we want to delete del
from the array arr
:
let arr = [1, 2, 3, 4, 5, 6];
let del = 4;
if (arr.indexOf(4) >= 0) {
arr.splice(arr.indexOf(4), 1)
}
Or
let del = 4;
for(var i = arr.length - 1; i >= 0; i--) {
if(arr[i] === del) {
arr.splice(i, 1);
}
}
If you know the element alone but not the position (or index) of the element, and want to delete just very first matching element using splice() method:
let arr = [1, 11, 2, 11, 3, 4, 5, 11, 6, 11];
for (let i = 0; i < arr.length-1; i++) {
if ( arr[i] === 11) {
arr.splice(i, 1);
break;
}
}
console.log(arr);
// [1, 11, 2, 11, 3, 4, 5, 11, 6, 11]
Take profit of reduce method as follows:
Case a) if you need to remove an element by index:
function remove(arr, index) {
return arr.reduce((prev, x, i) => prev.concat(i !== index ? [x] : []), []);
}
case b) if you need to remove an element by the value of the element (int):
function remove(arr, value) {
return arr.reduce((prev, x, i) => prev.concat(x !== value ? [x] : []), []);
}
So in this way we can return a new array (will be in a cool functional way - much better than using push or splice) with the element removed.
Splice, filter and delete to remove an element from an array
Every array has its index, and it helps to delete a particular element with their index.
The splice() method
array.splice(index, 1);
The first parameter is index and the second is the number of elements you want to delete from that index.
So for a single element, we use 1.
The delete method
delete array[index]
The filter() method
If you want to delete an element which is repeated in an array then filter the array:
removeAll = array.filter(e => e != elem);
Where elem
is the element you want to remove from the array and array
is your array name.
While most of the previous answers answer the question, it is not clear enough why the slice()
method has not been used. Yes, filter()
meets the immutability criteria, but how about doing the following shorter equivalent?
const myArray = [1,2,3,4];
And now let’s say that we should remove the second element from the array, we can simply do:
const newArray = myArray.slice(0, 1).concat(myArray.slice(2, 4));
// [1,3,4]
This way of deleting an element from an array is strongly encouraged today in the community due to its simple and immutable nature. In general, methods which cause mutation should be avoided. For example, you are encouraged to replace push()
with concat()
and splice()
with slice()
.
Vanilla JavaScript (ES5.1) – in place edition
Browser support: Internet Explorer 9 or later (detailed browser support)
/**
* Removes all occurences of the item from the array.
*
* Modifies the array “in place”, i.e. the array passed as an argument
* is modified as opposed to creating a new array. Also returns the modified
* array for your convenience.
*/
function removeInPlace(array, item) {
var foundIndex, fromIndex;
// Look for the item (the item can have multiple indices)
fromIndex = array.length - 1;
foundIndex = array.lastIndexOf(item, fromIndex);
while (foundIndex !== -1) {
// Remove the item (in place)
array.splice(foundIndex, 1);
// Bookkeeping
fromIndex = foundIndex - 1;
foundIndex = array.lastIndexOf(item, fromIndex);
}
// Return the modified array
return array;
}
Vanilla JavaScript (ES5.1) – immutable edition
Browser support: Same as vanilla JavaScript in place edition
/**
* Removes all occurences of the item from the array.
*
* Returns a new array with all the items of the original array except
* the specified item.
*/
function remove(array, item) {
var arrayCopy;
arrayCopy = array.slice();
return removeInPlace(arrayCopy, item);
}
Vanilla ES6 – immutable edition
Browser support: Chrome 46, Edge 12, Firefox 16, Opera 37, Safari 8 (detailed browser support)
/**
* Removes all occurences of the item from the array.
*
* Returns a new array with all the items of the original array except
* the specified item.
*/
function remove(array, item) {
// Copy the array
array = [...array];
// Look for the item (the item can have multiple indices)
let fromIndex = array.length - 1;
let foundIndex = array.lastIndexOf(item, fromIndex);
while (foundIndex !== -1) {
// Remove the item by generating a new array without it
array = [
...array.slice(0, foundIndex),
...array.slice(foundIndex + 1),
];
// Bookkeeping
fromIndex = foundIndex - 1;
foundIndex = array.lastIndexOf(item, fromIndex)
}
// Return the new array
return array;
}
A more modern, ECMAScript 2015 (formerly known as Harmony or ES 6) approach. Given:
const items = [1, 2, 3, 4];
const index = 2;
Then:
items.filter((x, i) => i !== index);
Yielding:
[1, 2, 4]
You can use Babel and a polyfill service to ensure this is well supported across browsers.
Beside all this solutions it can also be done with array.reduce...
const removeItem =
idx =>
arr =>
arr.reduce((acc, a, i) => idx === i ? acc : acc.concat(a), [])
const array = [1, 2, 3]
const index = 1
const newArray = removeItem(index)(array)
console.log(newArray) // logs the following array to the console : [1, 3]
... or a recursive function (which is to be honest not that elegant...has maybe someone a better recursive solution ??)...
const removeItemPrep =
acc =>
i =>
idx =>
arr =>
// If the index equals i, just feed in the unchanged accumulator(acc) else...
i === idx ? removeItemPrep(acc)(i + 1)(idx)(arr) :
// If the array length + 1 of the accumulator is smaller than the array length of the original array concatenate the array element at index i else...
acc.length + 1 < arr.length ? removeItemPrep(acc.concat(arr[i]))(i + 1)(idx)(arr) :
// return the accumulator
acc
const removeItem = removeItemPrep([])(0)
const array = [1, 2, 3]
const index = 1
const newArray = removeItem(index)(array)
console.log(newArray) // logs the following array to the console : [1, 3]
Understand this:
You can use JavaScript arrays to group values and iterate over them. Array items can be added and removed in a variety of ways. There are 9 ways in total (use any of these which suits you). Instead of a delete method, the JavaScript array has a variety of ways you can clean array values.
Different techniques ways of doing this:
you can use it to remove elements from JavaScript arrays in these ways:
1-pop: Removes from the End of an Array.
2-shift: Removes from the beginning of an Array.
3-splice: removes from a specific Array index.
4- filter: this allows you to programmatically remove elements from an Array.
Method 1: Removing Elements from the Beginning of a JavaScript Array
var ar = ['zero', 'one', 'two', 'three'];
ar.shift(); // returns "zero"
console.log( ar ); // ["one", "two", "three"]
Method 2: Removing Elements from the End of a JavaScript Array
var ar = [1, 2, 3, 4, 5, 6];
ar.length = 4; // set length to remove elements
console.log( ar ); // [1, 2, 3, 4]
var ar = [1, 2, 3, 4, 5, 6];
ar.pop(); // returns 6
console.log( ar ); // [1, 2, 3, 4, 5]
Method 3: Using Splice to Remove Array Elements in JavaScript
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var removed = arr.splice(2,2);
console.log(arr);
var list = ["bar", "baz", "foo", "qux"];
list.splice(0, 2);
console.log(list);
Method 4: Removing Array Items By Value Using Splice
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for( var i = 0; i < arr.length; i++){
if ( arr[i] === 5) {
arr.splice(i, 1);
}
}
//=> [1, 2, 3, 4, 6, 7, 8, 9, 10]
var arr = [1, 2, 3, 4, 5, 5, 6, 7, 8, 5, 9, 10];
for( var i = 0; i < arr.length; i++){
if ( arr[i] === 5) {
arr.splice(i, 1);
i--;
}
}
//=> [1, 2, 3, 4, 6, 7, 8, 9, 10]
Method 5: Using the Array filter Method to Remove Items By Value
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var filtered = array.filter(function(value, index, arr){
return value > 5;
});
//filtered => [6, 7, 8, 9]
//array => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Method 6: The Lodash Array Remove Method
var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
return n % 2 === 0;
});
console.log(array);// => [1, 3]console.log(evens);// => [2, 4]
Method 7: Making a Remove Method
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function arrayRemove(arr, value) {
return arr.filter(function(ele){
return ele != value;
});
}
var result = arrayRemove(array, 6); // result = [1, 2, 3, 4, 5, 7, 8, 9, 10]
method 8: Explicitly Remove Array Elements Using the Delete Operator
var ar = [1, 2, 3, 4, 5, 6];
delete ar[4]; // delete element with index 4
console.log( ar ); // [1, 2, 3, 4, undefined, 6]
alert( ar ); // 1,2,3,4,,6
Method 9: Clear or Reset a JavaScript Array
var ar = [1, 2, 3, 4, 5, 6];
//do stuffar = [];
//a new, empty array!
var arr1 = [1, 2, 3, 4, 5, 6];
var arr2 = arr1;
// Reference arr1 by another variable arr1 = [];
console.log(arr2);
// Output [1, 2, 3, 4, 5, 6]
var arr1 = [1, 2, 3, 4, 5, 6];
var arr2 = arr1;
// Reference arr1 by another variable arr1 = [];
console.log(arr2);
// Output [1, 2, 3, 4, 5, 6]
It's critical to manage your data by removing JavaScript Array items. Although there is no single "remove" function, you can purge unneeded array elements using a variety of ways and strategies.
**simple array**
const arr = ['1','2','3'];
const updatedArr = arr.filter(e => e !== '3');
console.warn(updatedArr);
**array of object**
const newArr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]
const updatedNewArr = newArr.filter(e => e.id !== 3);
console.warn(updatedNewArr);
**array of object with different parameter name**
const newArr = [{SINGLE_MDMC:{id:1,cout:10}},{BULK_MDMC:{id:1,cout:15}},{WPS_MDMC:{id:2,cout:10}},]
const newArray = newArr.filter((item) => !Object.keys(item).includes('SINGLE_MDMC'));
console.log(newArray)
const array = [1,2,3,4,5,6,7,8,9,0];
const index = array.indexOf(5);
// find Index of specific number
if(index != -1){
array.splice(index, 1); // remove number using index
}
console.log(array);
let array = [1, 2, 3, 4, 5, 1, 7, 8, 9, 2, 3, 4, 5, 6];
array = array.filter(number=> number !== 5);
console.log(array);
Using Join and split
let array = [1, 2, 3, 4, 5, 1, 7, 8, 9, 2, 3, 4, 5, 6]
array = Array.from(array.join("-").split("-5-").join("-").split("-"),Number)
console.log(array)
I want to answer based on ECMAScript 6. Assume you have an array like below:
let arr = [1,2,3,4];
If you want to delete at a special index like 2
, write the below code:
arr.splice(2, 1); //=> arr became [1,2,4]
But if you want to delete a special item like 3
and you don't know its index, do like below:
arr = arr.filter(e => e !== 3); //=> arr became [1,2,4]
Hint: please use an arrow function for filter callback unless you will get an empty array.
I just created a polyfill on the Array.prototype
via Object.defineProperty
to remove a desired element in an array without leading to errors when iterating over it later via for .. in ..
if (!Array.prototype.remove) {
// Object.definedProperty is used here to avoid problems when iterating with "for .. in .." in Arrays
// https://stackoverflow.com/questions/948358/adding-custom-functions-into-array-prototype
Object.defineProperty(Array.prototype, 'remove', {
value: function () {
if (this == null) {
throw new TypeError('Array.prototype.remove called on null or undefined')
}
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] === 'object') {
if (Object.keys(arguments[i]).length > 1) {
throw new Error('This method does not support more than one key:value pair per object on the arguments')
}
var keyToCompare = Object.keys(arguments[i])[0]
for (var j = 0; j < this.length; j++) {
if (this[j][keyToCompare] === arguments[i][keyToCompare]) {
this.splice(j, 1)
break
}
}
} else {
var index = this.indexOf(arguments[i])
if (index !== -1) {
this.splice(index, 1)
}
}
}
return this
}
})
} else {
var errorMessage = 'DANGER ALERT! Array.prototype.remove has already been defined on this browser. '
errorMessage += 'This may lead to unwanted results when remove() is executed.'
console.log(errorMessage)
}
Removing an integer value
var a = [1, 2, 3]
a.remove(2)
a // Output => [1, 3]
Removing a string value
var a = ['a', 'ab', 'abc']
a.remove('abc')
a // Output => ['a', 'ab']
Removing a boolean value
var a = [true, false, true]
a.remove(false)
a // Output => [true, true]
It is also possible to remove an object inside the array via this Array.prototype.remove
method. You just need to specify the key => value
of the Object
you want to remove.
Removing an object value
var a = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 3, b: 2}]
a.remove({a: 1})
a // Output => [{a: 2, b: 2}, {a: 3, b: 2}]
A very naive implementation would be as follows:
Array.prototype.remove = function(data) {
const dataIdx = this.indexOf(data)
if(dataIdx >= 0) {
this.splice(dataIdx ,1);
}
return this.length;
}
let a = [1,2,3];
// This will change arr a to [1, 3]
a.remove(2);
I return the length of the array from the function to comply with the other methods, like Array.prototype.push()
.
There are two major approaches to solve this problem:
You could write an utility function to remove an item from an array:
function removeItem(arr, value) {
const index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
const arr = ['apple', 'banana', 'grape', 'kiwi', 'apple', 'orange', 'banana'];
console.log(removeItem(arr, 'banana'));
// ['apple', 'grape', 'kiwi', apple', orange', 'banana']
You could see in the above code snippet, it only removes one match item (i.e. 'banana') and to remove all matching items from an array, you could try the following:
function removeAllItems(arr, value) {
let i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
const arr = ['apple', 'banana', 'grape', 'kiwi', 'apple', 'orange', 'banana'];
console.log(removeAllItems(arr, 'banana'));
// ['apple', 'grape', 'kiwi', apple', orange']
Array
Prototype:You could also add a function to the Array
object's prototype chain, which removes all the matching items:
Array.prototype.removeByValue = function (val) {
for (let i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
const arr = ['apple', 'banana', 'grape', 'kiwi', 'apple', 'orange', 'banana'];
arr.removeByValue('banana');
console.log(arr);
// ['apple', 'grape', 'kiwi', apple', orange']
I just used 'Array slice()' method:
const letterArray = ["a", "b", "c", "d", "e", "f"];//let's remove letter 'c'
const letterRemoval = letterArray.slice(0, 2);//this gives us new array ['a', 'b']
const joinArray = letterRemoval.concat(letterArray.slice(3));//let's merge two new arrays together
console.log(joinArray);
Use jQuery.grep():
var y = [1, 2, 3, 9, 4]
var removeItem = 9;
y = jQuery.grep(y, function(value) {
return value != removeItem;
});
console.log(y)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
The following method will remove all entries of a given value from an array without creating a new array and with only one iteration which is superfast. And it works in ancient Internet Explorer 5.5 browser:
function removeFromArray(arr, removeValue) {
for (var i = 0, k = 0, len = arr.length >>> 0; i < len; i++) {
if (k > 0)
arr[i - k] = arr[i];
if (arr[i] === removeValue)
k++;
}
for (; k--;)
arr.pop();
}
var a = [0, 1, 0, 2, 0, 3];
document.getElementById('code').innerHTML =
'Initial array [' + a.join(', ') + ']';
//Initial array [0, 1, 0, 2, 0, 3]
removeFromArray(a, 0);
document.getElementById('code').innerHTML +=
'<br>Resulting array [' + a.join(', ') + ']';
//Resulting array [1, 2, 3]
<code id="code"></code>
The two fastest ways that I love to use to remove an element from an array:
splice
methodfor
loopconst heartbreakerArray = ["","❤️","","❤️","❤️"]
// 1. If you want to remove only the first element from the array
const shallowCopy = Array.from(heartbreakerArray)
const index = shallowCopy.indexOf("❤️")
if (index > -1) { shallowCopy.splice(index, 1) }
console.log(shallowCopy) // Array(2) ["","","❤️","❤️"]
// 2. If you want to remove all matched elements from the array
const myOutputArray = []
const mySearchValue = "❤️"
for(let i = 0; i < heartbreakerArray.length; i++){
if(heartbreakerArray[i]!==mySearchValue) {
myOutputArray.push(heartbreakerArray[i])
}
}
console.log(myOutputArray) // Array(2) ["",""]
You can read the detailed blog post The fastest way to remove a specific item from an array in JavaScript.
I found this blog post which is showing nine ways to do it:
9 Ways to Remove Elements From A JavaScript Array - Plus How to Safely Clear JavaScript Arrays
I prefer to use filter()
:
var filtered_arr = arr.filter(function(ele){
return ele != value;
})
Remove element at index i, without mutating the original array:
/**
* removeElement
* @param {Array} array
* @param {Number} index
*/
function removeElement(array, index) {
return Array.from(array).splice(index, 1);
}
// Another way is
function removeElement(array, index) {
return array.slice(0).splice(index, 1);
}
2017-05-08
Most of the given answers work for strict comparison, meaning that both objects reference the exact same object in memory (or are primitive types), but often you want to remove a non-primitive object from an array that has a certain value. For instance, if you make a call to a server and want to check a retrieved object against a local object.
const a = {'field': 2} // Non-primitive object
const b = {'field': 2} // Non-primitive object with same value
const c = a // Non-primitive object that reference the same object as "a"
assert(a !== b) // Don't reference the same item, but have same value
assert(a === c) // Do reference the same item, and have same value (naturally)
//Note: there are many alternative implementations for valuesAreEqual
function valuesAreEqual (x, y) {
return JSON.stringify(x) === JSON.stringify(y)
}
//filter will delete false values
//Thus, we want to return "false" if the item
// we want to delete is equal to the item in the array
function removeFromArray(arr, toDelete){
return arr.filter(target => {return !valuesAreEqual(toDelete, target)})
}
const exampleArray = [a, b, b, c, a, {'field': 2}, {'field': 90}];
const resultArray = removeFromArray(exampleArray, a);
//resultArray = [{'field':90}]
There are alternative/faster implementations for valuesAreEqual, but this does the job. You can also use a custom comparator if you have a specific field to check (for example, some retrieved UUID vs a local UUID).
Also note that this is a functional operation, meaning that it does not mutate the original array.
OK, for example you have the array below:
var num = [1, 2, 3, 4, 5];
And we want to delete number 4. You can simply use the below code:
num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5];
If you are reusing this function, you write a reusable function which will be attached to the native array function like below:
Array.prototype.remove = Array.prototype.remove || function(x) {
const i = this.indexOf(x);
if(i===-1)
return;
this.splice(i, 1); // num.remove(5) === [1, 2, 3];
}
But how about if you have the below array instead with a few [5]s in the array?
var num = [5, 6, 5, 4, 5, 1, 5];
We need a loop to check them all, but an easier and more efficient way is using built-in JavaScript functions, so we write a function which use a filter like below instead:
const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6]
Also there are third-party libraries which do help you to do this, like Lodash or Underscore. For more information, look at lodash _.pull, _.pullAt or _.without.
The splice() function is able to give you back an item in the array as well as remove item / items from a specific index:
function removeArrayItem(index, array) {
array.splice(index, 1);
return array;
}
let array = [1,2,3,4];
let index = 2;
array = removeArrayItem(index, array);
console.log(array);
There are two major approaches
splice(): anArray.splice(index, 1);
let fruits = ['Apple', 'Banana', 'Mango', 'Orange']
let removed = fruits.splice(2, 1);
// fruits is ['Apple', 'Banana', 'Orange']
// removed is ['Mango']
delete: delete anArray[index];
let fruits = ['Apple', 'Banana', 'Mango', 'Orange']
let removed = delete fruits(2);
// fruits is ['Apple', 'Banana', undefined, 'Orange']
// removed is true
Be careful when you use the delete
for an array. It is good for deleting attributes of objects, but not so good for arrays. It is better to use splice
for arrays.
Keep in mind that when you use delete
for an array you could get wrong results for anArray.length
. In other words, delete
would remove the element, but it wouldn't update the value of the length property.
You can also expect to have holes in index numbers after using delete, e.g. you could end up with having indexes 1, 3, 4, 8, 9, and 11 and length as it was before using delete. In that case, all indexed for
loops would crash, since indexes are no longer sequential.
If you are forced to use delete
for some reason, then you should use for each
loops when you need to loop through arrays. As the matter of fact, always avoid using indexed for
loops, if possible. That way the code would be more robust and less prone to problems with indexes.
I would like to suggest to remove one array item using delete and filter:
var arr = [1,2,3,4,5,5,6,7,8,9];
delete arr[5];
arr = arr.filter(function(item){ return item != undefined; });
//result: [1,2,3,4,5,6,7,8,9]
console.log(arr)
So, we can remove only one specific array item instead of all items with the same value.
You can create an index with an all accessors example:
<div >
</div>
function getIndex($id){
return (
this.removeIndex($id)
alert("This element was removed")
)
}
function removeIndex(){
const index = $id;
this.accesor.id.splice(index.id) // You can use splice for slice index on
// accessor id and return with message
}
<div>
<fromList>
<ul>
{...this.array.map( accesors => {
<li type="hidden"></li>
<li>{...accesors}</li>
})
}
</ul>
</fromList>
<form id="form" method="post">
<input id="{this.accesors.id}">
<input type="submit" callbackforApplySend...getIndex({this.accesors.id}) name="sendendform" value="removeIndex" >
</form>
</div>
Most of the answers here give a solution using -
for loop
Although all the solutions should work with these methods, I thought we could use string manipulation.
Points to note about this solution -
The trick is to -
stringify
input data set and the search valuesplit
data on delimiter ,
. remove = (input, value) => {
const stringVal = JSON.stringify(value);
const result = JSON.stringify(input)
return result.replace(stringVal, "").split(",");
}
A JSFiddle with tests for objects and numbers is created here - https://jsfiddle.net/4t7zhkce/33/
Check the remove
method in the fiddle.
What a shame you have an array of integers, not an object where the keys are string equivalents of these integers.
I've looked through a lot of these answers and they all seem to use "brute force" as far as I can see. I haven't examined every single one, apologies if this is not so. For a smallish array this is fine, but what if you have 000s of integers in it?
Correct me if I'm wrong, but can't we assume that in a key => value
map, of the kind which a JavaScript object is, that the key retrieval mechanism can be assumed to be highly engineered and optimised? (NB: if some super-expert tells me that this is not the case, I can suggest using ECMAScript 6's Map class instead, which certainly will be).
I'm just suggesting that, in certain circumstances, the best solution might be to convert your array to an object... the problem being, of course, that you might have repeating integer values. I suggest putting those in buckets as the "value" part of the key => value
entries. (NB: if you are sure you don't have any repeating array elements this can be much simpler: values "same as" keys, and just go Object.values(...)
to get back your modified array).
So you could do:
const arr = [ 1, 2, 55, 3, 2, 4, 55 ];
const f = function( acc, val, currIndex ){
// We have not seen this value before: make a bucket... NB: although val's typeof is 'number',
// there is seamless equivalence between the object key (always string)
// and this variable val.
! ( val in acc ) ? acc[ val ] = []: 0;
// Drop another array index in the bucket
acc[ val ].push( currIndex );
return acc;
}
const myIntsMapObj = arr.reduce( f, {});
console.log( myIntsMapObj );
Output:
Object [ <1 empty slot>, Array1, Array[2], Array1, Array1, <5 empty slots>, 46 more… ]
It is then easy to delete all the numbers 55.
delete myIntsMapObj[ 55 ]; // Again, although keys are strings this works
You don't have to delete them all: index values are pushed into their buckets in order of appearance, so (for example):
myIntsMapObj[ 55 ].shift(); // And
myIntsMapObj[ 55 ].pop();
will delete the first and last occurrence respectively. You can count frequency of occurrence easily, replace all 55s with 3s by transferring the contents of one bucket to another, etc.
Retrieving a modified int
array from your "bucket object" is slightly involved but not so much: each bucket contains the index (in the original array) of the value represented by the (string
) key. Each of these bucket values is also unique (each is the unique index value in the original array): so you turn them into keys in a new object, with the (real) integer from the "integer string key" as value... then sort the keys and go Object.values( ... )
.
This sounds very involved and time-consuming... but obviously everything depends on the circumstances and desired usage. My understanding is that all versions and contexts of JavaScript operate only in one thread, and the thread doesn't "let go", so there could be some horrible congestion with a "brute force" method: caused not so much by the indexOf
ops, but multiple repeated slice
/splice
ops.
Addendum If you're sure this is too much engineering for your use case surely the simplest "brute force" approach is
const arr = [ 1, 2, 3, 66, 8, 2, 3, 2 ];
const newArray = arr.filter( number => number !== 3 );
console.log( newArray )
(Yes, other answers have spotted Array.prototype.filter
...)
Remove last occurrence or all occurrences, or first occurrence?
var array = [2, 5, 9, 5];
// Remove last occurrence (or all occurrences)
for (var i = array.length; i--;) {
if (array[i] === 5) {
array.splice(i, 1);
break; // Remove this line to remove all occurrences
}
}
or
var array = [2, 5, 9, 5];
// Remove first occurrence
for (var i = 0; array.length; i++) {
if (array[i] === 5) {
array.splice(i, 1);
break; // Do not remove this line
}
}
/**
* Removes one instance of `value` from `array`, without mutating the original array. Uses loose comparison.
*
* @param {Array} array Array to remove value from
* @param {*} value Value to remove
* @returns {Array} Array with `value` removed
*/
export function arrayRemove(array, value) {
for(let i=0; i<array.length; ++i) {
if(array[i] == value) {
let copy = [...array];
copy.splice(i, 1);
return copy;
}
}
return array;
}
In ES6, the Set collection provides a delete method to delete a specific value from the array, then convert the Set collection to an array by spread operator.
function deleteItem(list, val) {
const set = new Set(list);
set.delete(val);
return [...set];
}
const letters = ['A', 'B', 'C', 'D', 'E'];
console.log(deleteItem(letters, 'C')); // ['A', 'B', 'D', 'E']
There isn't any need to use indexOf
or splice
. However, it performs better if you only want to remove one occurrence of an element.
Find and move (move):
function move(arr, val) {
var j = 0;
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i] !== val) {
arr[j++] = arr[i];
}
}
arr.length = j;
}
Use indexOf
and splice
(indexof):
function indexof(arr, val) {
var i;
while ((i = arr.indexOf(val)) != -1) {
arr.splice(i, 1);
}
}
Use only splice
(splice):
function splice(arr, val) {
for (var i = arr.length; i--;) {
if (arr[i] === val) {
arr.splice(i, 1);
}
}
}
Run-times on Node.js for an array with 1000 elements (averaged over 10,000 runs):
indexof is approximately 10 times slower than move. Even if improved by removing the call to indexOf
in splice, it performs much worse than move.
Remove all occurrences:
move 0.0048 ms
indexof 0.0463 ms
splice 0.0359 ms
Remove first occurrence:
move_one 0.0041 ms
indexof_one 0.0021 ms
Array.prototype.removeItem = function(a) {
for (i = 0; i < this.length; i++) {
if (this[i] == a) {
for (i2 = i; i2 < this.length - 1; i2++) {
this[i2] = this[i2 + 1];
}
this.length = this.length - 1
return;
}
}
}
var recentMovies = ['Iron Man', 'Batman', 'Superman', 'Spiderman'];
recentMovies.removeItem('Superman');
Find the
index
of the array element you want to remove usingindexOf
, and then remove that index withsplice
.The second parameter of
splice
is the number of elements to remove. Note thatsplice
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:In TypeScript, these functions can stay type-safe with a type parameter: