How do I remove a specific value from an array? Something like:
array.remove(value); // removes all elements with value
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); // removes all elements with value
I have to use core JavaScript. Frameworks are not allowed.
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.
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');
An immutable and one-liner way:
const newArr = targetArr.filter(e => e !== elementToDelete);
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
removeNumber
, not a specific entry. So in your example, if there were other elements of 5
, they would also get removed, which is not what is wanted. Secondly, and closely tied to the first point, it's evaluating EVERY element in the array, so it's very inefficient if we know the index already. .filter() is evaluating every single element in the array with that condition.
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);
}
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]
Using the array filter method:
let array = [1, 2, 3, 4, 511, 34, 511, 78, 88];
let value = 511;
array = array.filter(element => element !== value);
console.log(array)
element.property !== value
filter
? (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today.)
Jan 2 at 16:16
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 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
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!
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);
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.
filter
removes every instance, splice
with indexOf
removes only the first.
splice
merely edits an existing array, whereas filter
creates a new array." I also linked the docs for both functions at the beginning. That they do different things should also be evident from their names.
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]
return value != elem
?!
I also ran into the situation where I had to remove an element from Array
. .indexOf
was not working in Internet Explorer, so I am sharing my working jQuery.inArray()
solution:
var index = jQuery.inArray(val, arr);
if (index > -1) {
arr.splice(index, 1);
//console.log(arr);
}
You can iterate over each array
-item and splice
it if it exist in your array
.
function destroy(arr, val) {
for (var i = 0; i < arr.length; i++) if (arr[i] === val) arr.splice(i, 1);
return arr;
}
Oftentimes it's better to just create a new array with the filter
function.
let array = [1,2,3,4];
array = array.filter(i => i !== 4); // [1,2,3]
This also improves readability IMHO. I'm not a fan of slice
, although it know sometimes you should go for it.
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.
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.
In CoffeeScript:
my_array.splice(idx, 1) for ele, idx in my_array when ele is this_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);
}
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.
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
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
...)
var array = [2, 5, 9];
var res = array.splice(array.findIndex(x => x==5), 1);
console.log(res)
Using Array.findindex, we can reduce the number of lines of code.
The simplest possible way to do this is probably using the filter function. Here's an example:
let array = ["hello", "world"]
let newarray = array.filter(item => item !== "hello");
console.log(newarray);
// ["world"]
Use jQuery's InArray:
A = [1, 2, 3, 4, 5, 6];
A.splice($.inArray(3, A), 1);
//It will return A=[1, 2, 4, 5, 6]`
Note: inArray will return -1, if the element was not found.
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;
})
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();
}
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']
indexOf()
+splice()
: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…array.filter((_, index) => index != number);
Array#push()
is well-known. (Of course, that is not what this question is asking for.)