efficient way to remove an object from an array of objects [duplicate] - javascript

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.

Find the index of the array element you want to remove using indexOf, and then remove that index with splice.
The splice() method changes the contents of an array by removing
existing elements and/or adding new elements.
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
array.splice(index, 1); // 2nd parameter means remove one item only
}
// array = [2, 9]
console.log(array);
The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.
For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
In TypeScript, these functions can stay type-safe with a type parameter:
function removeItem<T>(arr: Array<T>, value: T): Array<T> {
const index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}

Edited on 2016 October
Do it simple, intuitive and explicit (Occam's razor)
Do it immutable (original array stays unchanged)
Do it with standard JavaScript functions, if your browser doesn't support them - use polyfill
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.
Removing item (ECMA-262 Edition 5 code AKA old style JavaScript)
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 ]
Removing item (ECMAScript 6 code)
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.
Removing multiple items (ECMAScript 7 code)
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.
Removing multiple items (in the future, maybe)
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 ]
Try it yourself in BabelJS :)
Reference
Array.prototype.includes
Functional composition

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.

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.
Remove ALL instances from an array
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.

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.

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']

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

This provides a predicate instead of a value.
NOTE: it will update the given array, and return the affected rows.
Usage
var removed = helper.remove(arr, row => row.id === 5 );
var removed = helper.removeAll(arr, row => row.name.startsWith('BMW'));
Definition
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 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.

Using filter is an elegant way to achieve this requirement.
filter will not mutate 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]

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.

You can use ES6. For example to delete the value '3' in this case:
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
console.log(newArray);
Output :
["1", "2", "4", "5", "6"]

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]

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].

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.
If you know the index of an item
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.
If you know the value
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.
Removing multiple items
What if instead of a single item, you want to remove many items?
Let's find the simplest solution.
By index
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)
By value
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)
Avoid mutating the original array
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/)

Check out this code. It works in every major browser.
remove_item = function(arr, value) {
var b = '';
for (b in arr) {
if (arr[b] === value) {
arr.splice(b, 1);
break;
}
}
return arr;
};
var array = [1,3,5,6,5,9,5,3,55]
var res = remove_item(array,5);
console.log(res)

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']

ES10
This post summarizes common approaches to element removal from an array as of ECMAScript 2019 (ES10).
1. General cases
1.1. Removing Array element by value using .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]
1.2. Removing Array element using the .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 ]
1.3. Removing Array element by extending 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]
1.4. Removing Array element using the 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.
1.5. Removing Array element using 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]
2. Special cases
2.1 Removing element if it's at the end of the Array
2.1.1. Changing Array 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]
2.1.2. Using .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]
2.2. Removing element if it's at the beginning of the Array
| 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]
2.3. Removing element if it's the only element in the Array
| 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.

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']

ES6 & without mutation: (October 2016)
const removeByIndex = (list, index) =>
[
...list.slice(0, index),
...list.slice(index + 1)
];
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]
console.log(output)

Performance
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
the fastest solution is array.splice (C) (except Safari for small arrays where it has the second time)
for big arrays, array.slice+splice (H) is the fastest immutable solution for Firefox and Safari; Array.from (B) is fastest in Chrome
mutable solutions are usually 1.5x-6x faster than immutable
for small tables on Safari, surprisingly the mutable solution (C) is slower than the immutable solution (G)
Details
In 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

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.

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.

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.

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;
});

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]

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.

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.

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);

Related

Javascript : Opposite of deal.voters.push(user); [duplicate]

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.
Find the index of the array element you want to remove using indexOf, and then remove that index with splice.
The splice() method changes the contents of an array by removing
existing elements and/or adding new elements.
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
array.splice(index, 1); // 2nd parameter means remove one item only
}
// array = [2, 9]
console.log(array);
The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.
For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
In TypeScript, these functions can stay type-safe with a type parameter:
function removeItem<T>(arr: Array<T>, value: T): Array<T> {
const index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
Edited on 2016 October
Do it simple, intuitive and explicit (Occam's razor)
Do it immutable (original array stays unchanged)
Do it with standard JavaScript functions, if your browser doesn't support them - use polyfill
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.
Removing item (ECMA-262 Edition 5 code AKA old style JavaScript)
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 ]
Removing item (ECMAScript 6 code)
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.
Removing multiple items (ECMAScript 7 code)
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.
Removing multiple items (in the future, maybe)
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 ]
Try it yourself in BabelJS :)
Reference
Array.prototype.includes
Functional composition
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.
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.
Remove ALL instances from an array
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.
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.
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']
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
This provides a predicate instead of a value.
NOTE: it will update the given array, and return the affected rows.
Usage
var removed = helper.remove(arr, row => row.id === 5 );
var removed = helper.removeAll(arr, row => row.name.startsWith('BMW'));
Definition
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 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.
Using filter is an elegant way to achieve this requirement.
filter will not mutate 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]
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.
You can use ES6. For example to delete the value '3' in this case:
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
console.log(newArray);
Output :
["1", "2", "4", "5", "6"]
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]
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].
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.
If you know the index of an item
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.
If you know the value
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.
Removing multiple items
What if instead of a single item, you want to remove many items?
Let's find the simplest solution.
By index
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)
By value
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)
Avoid mutating the original array
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/)
Check out this code. It works in every major browser.
remove_item = function(arr, value) {
var b = '';
for (b in arr) {
if (arr[b] === value) {
arr.splice(b, 1);
break;
}
}
return arr;
};
var array = [1,3,5,6,5,9,5,3,55]
var res = remove_item(array,5);
console.log(res)
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']
ES10
This post summarizes common approaches to element removal from an array as of ECMAScript 2019 (ES10).
1. General cases
1.1. Removing Array element by value using .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]
1.2. Removing Array element using the .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 ]
1.3. Removing Array element by extending 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]
1.4. Removing Array element using the 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.
1.5. Removing Array element using 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]
2. Special cases
2.1 Removing element if it's at the end of the Array
2.1.1. Changing Array 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]
2.1.2. Using .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]
2.2. Removing element if it's at the beginning of the Array
| 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]
2.3. Removing element if it's the only element in the Array
| 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.
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']
ES6 & without mutation: (October 2016)
const removeByIndex = (list, index) =>
[
...list.slice(0, index),
...list.slice(index + 1)
];
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]
console.log(output)
Performance
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
the fastest solution is array.splice (C) (except Safari for small arrays where it has the second time)
for big arrays, array.slice+splice (H) is the fastest immutable solution for Firefox and Safari; Array.from (B) is fastest in Chrome
mutable solutions are usually 1.5x-6x faster than immutable
for small tables on Safari, surprisingly the mutable solution (C) is slower than the immutable solution (G)
Details
In 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
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.
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.
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.
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;
});
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]
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.
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.
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);

Remove One Object from Array using JavaScript [duplicate]

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.
Find the index of the array element you want to remove using indexOf, and then remove that index with splice.
The splice() method changes the contents of an array by removing
existing elements and/or adding new elements.
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
array.splice(index, 1); // 2nd parameter means remove one item only
}
// array = [2, 9]
console.log(array);
The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.
For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
In TypeScript, these functions can stay type-safe with a type parameter:
function removeItem<T>(arr: Array<T>, value: T): Array<T> {
const index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
Edited on 2016 October
Do it simple, intuitive and explicit (Occam's razor)
Do it immutable (original array stays unchanged)
Do it with standard JavaScript functions, if your browser doesn't support them - use polyfill
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.
Removing item (ECMA-262 Edition 5 code AKA old style JavaScript)
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 ]
Removing item (ECMAScript 6 code)
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.
Removing multiple items (ECMAScript 7 code)
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.
Removing multiple items (in the future, maybe)
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 ]
Try it yourself in BabelJS :)
Reference
Array.prototype.includes
Functional composition
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.
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.
Remove ALL instances from an array
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.
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.
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']
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
This provides a predicate instead of a value.
NOTE: it will update the given array, and return the affected rows.
Usage
var removed = helper.remove(arr, row => row.id === 5 );
var removed = helper.removeAll(arr, row => row.name.startsWith('BMW'));
Definition
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 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.
Using filter is an elegant way to achieve this requirement.
filter will not mutate 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]
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.
You can use ES6. For example to delete the value '3' in this case:
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
console.log(newArray);
Output :
["1", "2", "4", "5", "6"]
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]
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].
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.
If you know the index of an item
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.
If you know the value
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.
Removing multiple items
What if instead of a single item, you want to remove many items?
Let's find the simplest solution.
By index
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)
By value
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)
Avoid mutating the original array
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/)
Check out this code. It works in every major browser.
remove_item = function(arr, value) {
var b = '';
for (b in arr) {
if (arr[b] === value) {
arr.splice(b, 1);
break;
}
}
return arr;
};
var array = [1,3,5,6,5,9,5,3,55]
var res = remove_item(array,5);
console.log(res)
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']
ES10
This post summarizes common approaches to element removal from an array as of ECMAScript 2019 (ES10).
1. General cases
1.1. Removing Array element by value using .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]
1.2. Removing Array element using the .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 ]
1.3. Removing Array element by extending 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]
1.4. Removing Array element using the 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.
1.5. Removing Array element using 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]
2. Special cases
2.1 Removing element if it's at the end of the Array
2.1.1. Changing Array 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]
2.1.2. Using .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]
2.2. Removing element if it's at the beginning of the Array
| 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]
2.3. Removing element if it's the only element in the Array
| 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.
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']
ES6 & without mutation: (October 2016)
const removeByIndex = (list, index) =>
[
...list.slice(0, index),
...list.slice(index + 1)
];
output = removeByIndex([33,22,11,44],1) //=> [33,11,44]
console.log(output)
Performance
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
the fastest solution is array.splice (C) (except Safari for small arrays where it has the second time)
for big arrays, array.slice+splice (H) is the fastest immutable solution for Firefox and Safari; Array.from (B) is fastest in Chrome
mutable solutions are usually 1.5x-6x faster than immutable
for small tables on Safari, surprisingly the mutable solution (C) is slower than the immutable solution (G)
Details
In 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
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.
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.
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.
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;
});
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]
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.
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.
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);

Merging of two arrays, store unique elements, and sorting in jQuery

var Arr1 = [1,3,4,5,6];
var Arr2 = [4,5,6,8,9,10];
I am trying to do merge these two arrays and output coming is [1,3,4,5,6,4,5,6]
I have used $.merge(Arr1, Arr2); this piece to merge them. Using alert I can see the merged array like above.
Now my question is how can I get the following output:
[1,3,4,5,6,8,9,10]
i.e. the elements should be unique as well as sorted in the same manner I have mentioned.
Please help.
You can use Array.prototype.sort() to do a real numeric sort and use Array.prototype.filter() to only return the unique elements.
You can wrap it into a helper similar to this:
var concatArraysUniqueWithSort = function (thisArray, otherArray) {
var newArray = thisArray.concat(otherArray).sort(function (a, b) {
return a > b ? 1 : a < b ? -1 : 0;
});
return newArray.filter(function (item, index) {
return newArray.indexOf(item) === index;
});
};
Note that the custom sort function works with numeric elements only, so if you want to use it for strings or mix strings with numbers you have to update it off course to take those scenarios into account, though the rest should not change much.
Use it like this:
var arr1 = [1, 3, 4, 5, 6];
var arr2 = [4, 5, 6, 8, 9, 10];
var arrAll = concatArraysUniqueWithSort(arr1, arr2);
arrAll will now be [1, 3, 4, 5, 6, 8, 9, 10]
DEMO - concatenate 2 arrays, sort and remove duplicates
There is many ways of doing this I'm sure. This was just the most concise I could think off.
merge two or more arrays + remove duplicities + sort()
jQuery.unique([].concat.apply([],[[1,2,3,4],[1,2,3,4,5,6],[3,4,5,6,7,8]])).sort();
One line solution using just javascript.
var Arr1 = [1,3,4,5,6];
var Arr2 = [4,5,6,8,9,10];
const sortedUnion = [... new Set([...Arr1,... Arr2].sort((a,b)=> a-b))]
console.log(sortedUnion)
This looks like a job for Array.prototype.indexOf
var arr3 = arr1.slice(), // clone arr1 so no side-effects
i; // var i so it 's not global
for (i = 0; i < arr2.length; ++i) // loop over arr2
if (arr1.indexOf(arr2[i]) === -1) // see if item from arr2 is in arr1 or not
arr3.push(arr2[i]); // it's not, add it to arr3
arr3.sort(function (a, b) {return a - b;});
arr3; // [1, 3, 4, 5, 6, 8, 9, 10]
a = [1, 2, 3]
b = [2, 3, 4]
$.unique($.merge(a, b)).sort(function(a,b){return a-b}); -> [1, 2, 3, 4]
Update:
This is a bad idea, since the 'unique' function is not meant for use on numbers or strings.
However, if you must then the sort function needs to be told to use a new comparator since by default it sorts lexicographically.
Using underscore.js:
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]).sort(function(a,b){return a-b});
=> [1, 2, 3, 10, 101]
This example is taken directly from underscore.js, a popular JS library which complements jQuery
I did that as follows, where t1 and t2 are my two tables.
The first command put the values of the table t2 to the t1. The second command removes the duplicate values from the table.
$.merge(t1, t2);
$.unique(t1);
function sortUnique(matrix) {
if(matrix.length < 1 || matrix[0].length < 1) return [];
const result = [];
let temp, ele;
while(matrix.length > 0) {
temp = 0;
for(let j=0; j<matrix.length; j++) {
if(matrix[j][0] < matrix[temp][0]) temp = j;
}
if(result.length === 0 || matrix[temp][0] > result[result.length-1]) {
result.push(matrix[temp].splice(0,1)[0]);
} else {
matrix[temp].splice(0,1);
}
if(matrix[temp].length===0) matrix.splice(temp, 1);
}
return result;
}
console.log(sortUnique([[1,4,8], [2,4,9], [1,2,7]]))
Using JavaScript ES6 makes it easier and cleaner. Try this:
return [...Arr1, ...Arr2].filter((v,i,s) => s.indexOf(v) === i).sort((a,b)=> a - b);
and there you have it. You could build it in a function like:
function mergeUniqueSort(Arr1, Arr2){
return [...Arr1, ...Arr2].filter((v,i,s) => s.indexOf(v) === i).sort((a,b)=> a - b);
}
and that settles it. You can also break it down using ES6. Use a Spread Operator to combine arrays:
let combinedArrays = [...Arr1, ...Arr2]
then get the unique elements using the filter function:
let uniqueValues = combinedArrays.filter((value, index, self ) => self.indexOf(value) === index)
Lastly you now sort the uniqueValue object:
let sortAscending = uniqueValues.sort((a-b) => a - b) // 1, 2, 3, ....10
let sortDescending = uniqueValues.sort((b-a) => b - a) // 10, 9, 8, ....1
So you could use any part, just in case.

Remove multiple elements from array in Javascript/jQuery

I have two arrays. The first array contains some values while the second array contains indices of the values which should be removed from the first array. For example:
var valuesArr = new Array("v1","v2","v3","v4","v5");
var removeValFromIndex = new Array(0,2,4);
I want to remove the values present at indices 0,2,4 from valuesArr. I thought the native splice method might help so I came up with:
$.each(removeValFromIndex,function(index,value){
valuesArr.splice(value,1);
});
But it didn't work because after each splice, the indices of the values in valuesArr were different. I could solve this problem by using a temporary array and copying all values to the second array, but I was wondering if there are any native methods to which we can pass multiple indices at which to remove values from an array.
I would prefer a jQuery solution. (Not sure if I can use grep here)
There's always the plain old for loop:
var valuesArr = ["v1","v2","v3","v4","v5"],
removeValFromIndex = [0,2,4];
for (var i = removeValFromIndex.length -1; i >= 0; i--)
valuesArr.splice(removeValFromIndex[i],1);
Go through removeValFromIndex in reverse order and you can .splice() without messing up the indexes of the yet-to-be-removed items.
Note in the above I've used the array-literal syntax with square brackets to declare the two arrays. This is the recommended syntax because new Array() use is potentially confusing given that it responds differently depending on how many parameters you pass in.
EDIT: Just saw your comment on another answer about the array of indexes not necessarily being in any particular order. If that's the case just sort it into descending order before you start:
removeValFromIndex.sort(function(a,b){ return b - a; });
And follow that with whatever looping / $.each() / etc. method you like.
I suggest you use Array.prototype.filter
var valuesArr = ["v1","v2","v3","v4","v5"];
var removeValFrom = [0, 2, 4];
valuesArr = valuesArr.filter(function(value, index) {
return removeValFrom.indexOf(index) == -1;
})
Here is one that I use when not going with lodash/underscore:
while(IndexesToBeRemoved.length) {
elements.splice(IndexesToBeRemoved.pop(), 1);
}
Not in-place but can be done using grep and inArray functions of jQuery.
var arr = $.grep(valuesArr, function(n, i) {
return $.inArray(i, removeValFromIndex) ==-1;
});
alert(arr);//arr contains V2, V4
check this fiddle.
A simple and efficient (linear complexity) solution using filter and Set:
const valuesArr = ['v1', 'v2', 'v3', 'v4', 'v5'];
const removeValFromIndex = [0, 2, 4];
const indexSet = new Set(removeValFromIndex);
const arrayWithValuesRemoved = valuesArr.filter((value, i) => !indexSet.has(i));
console.log(arrayWithValuesRemoved);
The great advantage of that implementation is that the Set lookup operation (has function) takes a constant time, being faster than nevace's answer, for example.
This works well for me and work when deleting from an array of objects too:
var array = [
{ id: 1, name: 'bob', faveColor: 'blue' },
{ id: 2, name: 'jane', faveColor: 'red' },
{ id: 3, name: 'sam', faveColor: 'blue' }
];
// remove people that like blue
array.filter(x => x.faveColor === 'blue').forEach(x => array.splice(array.indexOf(x), 1));
There might be a shorter more effecient way to write this but this does work.
It feels necessary to post an answer with O(n) time :). The problem with the splice solution is that due to the underlying implementation of array being literally an array, each splice call will take O(n) time. This is most pronounced when we setup an example to exploit this behavior:
var n = 100
var xs = []
for(var i=0; i<n;i++)
xs.push(i)
var is = []
for(var i=n/2-1; i>=0;i--)
is.push(i)
This removes elements starting from the middle to the start, hence each remove forces the js engine to copy n/2 elements, we have (n/2)^2 copy operations in total which is quadratic.
The splice solution (assuming is is already sorted in decreasing order to get rid of overheads) goes like this:
for(var i=0; i<is.length; i++)
xs.splice(is[i], 1)
However, it is not hard to implement a linear time solution, by re-constructing the array from scratch, using a mask to see if we copy elements or not (sort will push this to O(n)log(n)). The following is such an implementation (not that mask is boolean inverted for speed):
var mask = new Array(xs.length)
for(var i=is.length - 1; i>=0; i--)
mask[is[i]] = true
var offset = 0
for(var i=0; i<xs.length; i++){
if(mask[i] === undefined){
xs[offset] = xs[i]
offset++
}
}
xs.length = offset
I ran this on jsperf.com and for even n=100 the splice method is a full 90% slower. For larger n this difference will be much greater.
I find this the most elegant solution:
const oldArray = [1, 2, 3, 4, 5]
const removeItems = [1, 3, 5]
const newArray = oldArray.filter((value) => {
return !removeItems.includes(value)
})
console.log(newArray)
output:
[2, 4]
or even shorter:
const newArray = oldArray.filter(v => !removeItems.includes(v))
function filtermethod(element, index, array) {
return removeValFromIndex.find(index)
}
var result = valuesArr.filter(filtermethod);
MDN reference is here
In pure JS you can loop through the array backwards, so splice() will not mess up indices of the elements next in the loop:
for (var i = arr.length - 1; i >= 0; i--) {
if ( yuck(arr[i]) ) {
arr.splice(i, 1);
}
}
A simple solution using ES5. This seems more appropriate for most applications nowadays, since many do no longer want to rely on jQuery etc.
When the indexes to be removed are sorted in ascending order:
var valuesArr = ["v1", "v2", "v3", "v4", "v5"];
var removeValFromIndex = [0, 2, 4]; // ascending
removeValFromIndex.reverse().forEach(function(index) {
valuesArr.splice(index, 1);
});
When the indexes to be removed are not sorted:
var valuesArr = ["v1", "v2", "v3", "v4", "v5"];
var removeValFromIndex = [2, 4, 0]; // unsorted
removeValFromIndex.sort(function(a, b) { return b - a; }).forEach(function(index) {
valuesArr.splice(index, 1);
});
Quick ES6 one liner:
const valuesArr = new Array("v1","v2","v3","v4","v5");
const removeValFromIndex = new Array(0,2,4);
const arrayWithValuesRemoved = valuesArr.filter((value, i) => removeValFromIndex.includes(i))
If you are using underscore.js, you can use _.filter() to solve your problem.
var valuesArr = new Array("v1","v2","v3","v4","v5");
var removeValFromIndex = new Array(0,2,4);
var filteredArr = _.filter(valuesArr, function(item, index){
return !_.contains(removeValFromIndex, index);
});
Additionally, if you are trying to remove items using a list of items instead of indexes, you can simply use _.without(), like so:
var valuesArr = new Array("v1","v2","v3","v4","v5");
var filteredArr = _.without(valuesArr, "V1", "V3");
Now filteredArr should be ["V2", "V4", "V5"]
You can correct your code by replacing removeValFromIndex with removeValFromIndex.reverse(). If that array is not guaranteed to use ascending order, you can instead use removeValFromIndex.sort(function(a, b) { return b - a }).
Here's one possibility:
valuesArr = removeValFromIndex.reduceRight(function (arr, it) {
arr.splice(it, 1);
return arr;
}, valuesArr.sort(function (a, b) { return b - a }));
Example on jsFiddle
MDN on Array.prototype.reduceRight
filter + indexOf (IE9+):
function removeMany(array, indexes) {
return array.filter(function(_, idx) {
return indexes.indexOf(idx) === -1;
});
});
Or with ES6 filter + find (Edge+):
function removeMany(array, indexes = []) {
return array.filter((_, idx) => indexes.indexOf(idx) === -1)
}
Here's a quickie.
function removeFromArray(arr, toRemove){
return arr.filter(item => toRemove.indexOf(item) === -1)
}
const arr1 = [1, 2, 3, 4, 5, 6, 7]
const arr2 = removeFromArray(arr1, [2, 4, 6]) // [1,3,5,7]
Try this
var valuesArr = new Array("v1", "v2", "v3", "v4", "v5");
console.info("Before valuesArr = " + valuesArr);
var removeValFromIndex = new Array(0, 2, 4);
valuesArr = valuesArr.filter((val, index) => {
return !removeValFromIndex.includes(index);
})
console.info("After valuesArr = " + valuesArr);
Sounds like Apply could be what you are looking for.
maybe something like this would work?
Array.prototype.splice.apply(valuesArray, removeValFromIndexes );
var valuesArr = new Array("v1","v2","v3","v4","v5");
var removeValFromIndex = new Array(0,2,4);
console.log(valuesArr)
let arr2 = [];
for (let i = 0; i < valuesArr.length; i++){
if ( //could also just imput this below instead of index value
valuesArr[i] !== valuesArr[0] && // "v1" <--
valuesArr[i] !== valuesArr[2] && // "v3" <--
valuesArr[i] !== valuesArr[4] // "v5" <--
){
arr2.push(valuesArr[i]);
}
}
console.log(arr2);
This works. However, you would make a new array in the process. Not sure if thats would you want or not, but technically it would be an array containing only the values you wanted.
You can try Lodash js library functions (_.forEach(), _.remove()). I was using this technique to remove multiple rows from the table.
let valuesArr = [
{id: 1, name: "dog"},
{id: 2, name: "cat"},
{id: 3, name: "rat"},
{id: 4, name: "bat"},
{id: 5, name: "pig"},
];
let removeValFromIndex = [
{id: 2, name: "cat"},
{id: 5, name: "pig"},
];
_.forEach(removeValFromIndex, (indi) => {
_.remove(valuesArr, (item) => {
return item.id === indi.id;
});
})
console.log(valuesArr)
/*[
{id: 1, name: "dog"},
{id: 3, name: "rat"},
{id: 4, name: "bat"},
];*/
Don't forget to clone (_.clone(valuesArr) or [...valuesArr]) before mutate your array
You could try and use delete array[index] This won't completely remove the element but rather sets the value to undefined.
removeValFromIndex.forEach(function(toRemoveIndex){
valuesArr.splice(toRemoveIndex,1);
});
For Multiple items or unique item:
I suggest you use Array.prototype.filter
Don't ever use indexOf if you already know the index!:
var valuesArr = ["v1","v2","v3","v4","v5"];
var removeValFrom = [0, 2, 4];
valuesArr = valuesArr.filter(function(value, index) {
return removeValFrom.indexOf(index) == -1;
}); // BIG O(N*m) where N is length of valuesArr and m is length removeValFrom
Do:
with Hashes... using Array.prototype.map
var valuesArr = ["v1","v2","v3","v4","v5"];
var removeValFrom = {};
([0, 2, 4]).map(x=>removeValFrom[x]=1); //bild the hash.
valuesArr = valuesArr.filter(function(value, index) {
return removeValFrom[index] == 1;
}); // BIG O(N) where N is valuesArr;
You could construct a Set from the array and then create an array from the set.
const array = [1, 1, 2, 3, 5, 5, 1];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Result: [1, 2, 3, 5]

How to count certain elements in array?

I have an array:
[1, 2, 3, 5, 2, 8, 9, 2]
I would like to know how many 2s are in the array.
What is the most elegant way to do it in JavaScript without looping with for loop?
[this answer is a bit dated: read the edits, in the notion of 'equal' in javascript is ambiguous]
Say hello to your friends: map and filter and reduce and forEach and every etc.
(I only occasionally write for-loops in javascript, because of block-level scoping is missing, so you have to use a function as the body of the loop anyway if you need to capture or clone your iteration index or value. For-loops are more efficient generally, but sometimes you need a closure.)
The most readable way:
[....].filter(x => x==2).length
(We could have written .filter(function(x){return x==2}).length instead)
The following is more space-efficient (O(1) rather than O(N)), but I'm not sure how much of a benefit/penalty you might pay in terms of time (not more than a constant factor since you visit each element exactly once):
[....].reduce((total,x) => (x==2 ? total+1 : total), 0)
or as a commenter kindly pointed out:
[....].reduce((total,x) => total+(x==2), 0)
(If you need to optimize this particular piece of code, a for loop might be faster on some browsers... you can test things on jsperf.com.)
You can then be elegant and turn it into a prototype function:
[1, 2, 3, 5, 2, 8, 9, 2].count(2)
Like this:
Object.defineProperties(Array.prototype, {
count: {
value: function(value) {
return this.filter(x => x==value).length;
}
}
});
You can also stick the regular old for-loop technique (see other answers) inside the above property definition (again, that would likely be much faster).
2017 edit:
Whoops, this answer has gotten more popular than the correct answer. Actually, just use the accepted answer. While this answer may be cute, the js compilers probably don't (or can't due to spec) optimize such cases. So you should really write a simple for loop:
Object.defineProperties(Array.prototype, {
count: {
value: function(query) {
/*
Counts number of occurrences of query in array, an integer >= 0
Uses the javascript == notion of equality.
*/
var count = 0;
for(let i=0; i<this.length; i++)
if (this[i]==query)
count++;
return count;
}
}
});
You could define a version .countStrictEq(...) which used the === notion of equality. The notion of equality may be important to what you're doing! (for example [1,10,3,'10'].count(10)==2, because numbers like '4'==4 in javascript... hence calling it .countEq or .countNonstrict stresses it uses the == operator.)
Caveat:
Defining a common name on the prototype should be done with care. It is fine if you control your code, but bad if everyone wants to declare their own [].count function, especially if they behave differently. You may ask yourself "but .count(query) surely sounds quite perfect and canonical"... but consider perhaps you could do something like [].count(x=> someExpr of x). In that case you define functions like countIn(query, container) (under myModuleName.countIn), or something, or [].myModuleName_count().
Also consider using your own multiset data structure (e.g. like python's 'collections.Counter') to avoid having to do the counting in the first place. This works for exact matches of the form [].filter(x=> x==???).length (worst case O(N) down to O(1)), and modified will speed up queries of the form [].filter(filterFunction).length (roughly by a factor of #total/#duplicates).
class Multiset extends Map {
constructor(...args) {
super(...args);
}
add(elem) {
if (!this.has(elem))
this.set(elem, 1);
else
this.set(elem, this.get(elem)+1);
}
remove(elem) {
var count = this.has(elem) ? this.get(elem) : 0;
if (count>1) {
this.set(elem, count-1);
} else if (count==1) {
this.delete(elem);
} else if (count==0)
throw `tried to remove element ${elem} of type ${typeof elem} from Multiset, but does not exist in Multiset (count is 0 and cannot go negative)`;
// alternatively do nothing {}
}
}
Demo:
> counts = new Multiset([['a',1],['b',3]])
Map(2) {"a" => 1, "b" => 3}
> counts.add('c')
> counts
Map(3) {"a" => 1, "b" => 3, "c" => 1}
> counts.remove('a')
> counts
Map(2) {"b" => 3, "c" => 1}
> counts.remove('a')
Uncaught tried to remove element a of type string from Multiset, but does not exist in Multiset (count is 0 and cannot go negative)
sidenote: Though, if you still wanted the functional-programming way (or a throwaway one-liner without overriding Array.prototype), you could write it more tersely nowadays as [...].filter(x => x==2).length. If you care about performance, note that while this is asymptotically the same performance as the for-loop (O(N) time), it may require O(N) extra memory (instead of O(1) memory) because it will almost certainly generate an intermediate array and then count the elements of that intermediate array.
Modern JavaScript:
Note that you should always use triple equals === when doing comparison in JavaScript (JS). The triple equals make sure, that JS comparison behaves like double equals == in other languages (there is one exception, see below). The following solution shows how to solve this the functional way, which will ensure that you will never have out of bounds error:
// Let has local scope
let array = [1, 2, 3, 5, 2, 8, 9, 2]
// Functional filter with an Arrow function
// Filter all elements equal to 2 and return the length (count)
array.filter(x => x === 2).length // -> 3
The following anonymous Arrow function (lambda function) in JavaScript:
(x) => {
const k = 2
return k * x
}
may be simplified to this concise form for a single input:
x => 2 * x
where the return is implied.
Always use triple equals: === for comparison in JS, with the exception of when checking for nullability: if (something == null) {} as it includes a check for undefined, if you only use double equals as in this case.
Very simple:
var count = 0;
for(var i = 0; i < array.length; ++i){
if(array[i] == 2)
count++;
}
2017:
If someone is still interested in the question, my solution is the following:
const arrayToCount = [1, 2, 3, 5, 2, 8, 9, 2];
const result = arrayToCount.filter(i => i === 2).length;
console.log('number of the found elements: ' + result);
Here is an ES2017+ way to get the counts for all array items in O(N):
const arr = [1, 2, 3, 5, 2, 8, 9, 2];
const counts = {};
arr.forEach((el) => {
counts[el] = counts[el] ? (counts[el] + 1) : 1;
});
You can also optionally sort the output:
const countsSorted = Object.entries(counts).sort(([_, a], [__, b]) => a - b);
console.log(countsSorted) for your example array:
[
[ '2', 3 ],
[ '1', 1 ],
[ '3', 1 ],
[ '5', 1 ],
[ '8', 1 ],
[ '9', 1 ]
]
If you are using lodash or underscore the _.countBy method will provide an object of aggregate totals keyed by each value in the array. You can turn this into a one-liner if you only need to count one value:
_.countBy(['foo', 'foo', 'bar'])['foo']; // 2
This also works fine on arrays of numbers. The one-liner for your example would be:
_.countBy([1, 2, 3, 5, 2, 8, 9, 2])[2]; // 3
Weirdest way I can think of doing this is:
(a.length-(' '+a.join(' ')+' ').split(' '+n+' ').join(' ').match(/ /g).length)+1
Where:
a is the array
n is the number to count in the array
My suggestion, use a while or for loop ;-)
Not using a loop usually means handing the process over to some method that does use a loop.
Here is a way our loop hating coder can satisfy his loathing, at a price:
var a=[1, 2, 3, 5, 2, 8, 9, 2];
alert(String(a).replace(/[^2]+/g,'').length);
/* returned value: (Number)
3
*/
You can also repeatedly call indexOf, if it is available as an array method, and move the search pointer each time.
This does not create a new array, and the loop is faster than a forEach or filter.
It could make a difference if you have a million members to look at.
function countItems(arr, what){
var count= 0, i;
while((i= arr.indexOf(what, i))!= -1){
++count;
++i;
}
return count
}
countItems(a,2)
/* returned value: (Number)
3
*/
I'm a begin fan of js array's reduce function.
const myArray =[1, 2, 3, 5, 2, 8, 9, 2];
const count = myArray.reduce((count, num) => num === 2 ? count + 1 : count, 0)
In fact if you really want to get fancy you can create a count function on the Array prototype. Then you can reuse it.
Array.prototype.count = function(filterMethod) {
return this.reduce((count, item) => filterMethod(item)? count + 1 : count, 0);
}
Then do
const myArray =[1, 2, 3, 5, 2, 8, 9, 2]
const count = myArray.count(x => x==2)
Most of the posted solutions using array functions such as filter are incomplete because they aren't parameterized.
Here goes a solution with which the element to count can be set at run time.
function elementsCount(elementToFind, total, number){
return total += number==elementToFind;
}
var ar = [1, 2, 3, 5, 2, 8, 9, 2];
var elementToFind=2;
var result = ar.reduce(elementsCount.bind(this, elementToFind), 0);
The advantage of this approach is that could easily change the function to count for instance the number of elements greater than X.
You may also declare the reduce function inline
var ar = [1, 2, 3, 5, 2, 8, 9, 2];
var elementToFind=2;
var result = ar.reduce(function (elementToFind, total, number){
return total += number==elementToFind;
}.bind(this, elementToFind), 0);
Really, why would you need map or filter for this?
reduce was "born" for these kind of operations:
[1, 2, 3, 5, 2, 8, 9, 2].reduce( (count,2)=>count+(item==val), 0);
that's it! (if item==val in each iteration, then 1 will be added to the accumulator count, as true will resolve to 1).
As a function:
function countInArray(arr, val) {
return arr.reduce((count,item)=>count+(item==val),0)
}
Or, go ahead and extend your arrays:
Array.prototype.count = function(val) {
return this.reduce((count,item)=>count+(item==val),0)
}
It is better to wrap it into function:
let countNumber = (array,specificNumber) => {
return array.filter(n => n == specificNumber).length
}
countNumber([1,2,3,4,5],3) // returns 1
I use this:
function countElement(array, element) {
let tot = 0;
for(var el of array) {
if(el == element) {
tot++;
}
}
return tot;
}
var arr = ["a", "b", "a", "c", "d", "a", "e", "f", "a"];
console.log(countElement(arr, "a")); // 4
var arrayCount = [1,2,3,2,5,6,2,8];
var co = 0;
function findElement(){
arrayCount.find(function(value, index) {
if(value == 2)
co++;
});
console.log( 'found' + ' ' + co + ' element with value 2');
}
I would do something like that:
var arrayCount = [1,2,3,4,5,6,7,8];
function countarr(){
var dd = 0;
arrayCount.forEach( function(s){
dd++;
});
console.log(dd);
}
I believe what you are looking for is functional approach
const arr = ['a', 'a', 'b', 'g', 'a', 'e'];
const count = arr.filter(elem => elem === 'a').length;
console.log(count); // Prints 3
elem === 'a' is the condition, replace it with your own.
Array.prototype.count = function (v) {
var c = 0;
for (let i = 0; i < this.length; i++) {
if(this[i] === v){
c++;
}
}
return c;
}
var arr = [1, 2, 3, 5, 2, 8, 9, 2];
console.log(arr.count(2)); //3
Solution by recursion
function count(arr, value) {
if (arr.length === 1) {
return arr[0] === value ? 1 : 0;
} else {
return (arr.shift() === value ? 1 : 0) + count(arr, value);
}
}
count([1,2,2,3,4,5,2], 2); // 3
Create a new method for Array class in core level file and use it all over your project.
// say in app.js
Array.prototype.occurrence = function(val) {
return this.filter(e => e === val).length;
}
Use this anywhere in your project -
[1, 2, 4, 5, 2, 7, 2, 9].occurrence(2);
// above line returns 3
Here is a one liner in javascript.
Use map. Find the matching values (v === 2) in the array, returning an array of ones and zeros.
Use Reduce. Add all the values of the array for the total number found.
[1, 2, 3, 5, 2, 8, 9, 2]
.map(function(v) {
return v === 2 ? 1 : 0;
})
.reduce((a, b) => a + b, 0);
The result is 3.
Depending on how you want to run it:
const reduced = (array, val) => { // self explanatory
return array.filter((element) => element === val).length;
}
console.log(reduced([1, 2, 3, 5, 2, 8, 9, 2], 2));
// 3
const reducer = (array) => { // array to set > set.forEach > map.set
const count = new Map();
const values = new Set(array);
values.forEach((element)=> {
count.set(element, array.filter((arrayElement) => arrayElement === element).length);
});
return count;
}
console.log(reducer([1, 2, 3, 5, 2, 8, 9, 2]));
// Map(6) {1 => 1, 2 => 3, 3 => 1, 5 => 1, 8 => 1, …}
You can use built-in function Array.filter()
array.filter(x => x === element).length;
var arr = [1, 2, 3, 5, 2, 8, 9, 2];
// Count how many 2 there are in arr
var count = arr.filter(x => x === 2).length;
console.log(count);
One-liner function
const countBy = (a,f)=>a.reduce((p,v,i,x)=>p+!!f(v,i,x), 0)
countBy([1,2,3,4,5], v=>v%2===0) // 2
There are many ways to find out. I think the easiest way is to use the array filter method which is introduced in es6.
function itemCount(array, item) {
return array.filter(element => element === item).length
}
const myArray = [1,3,5,7,1,2,3,4,5,1,9,0,1]
const items = itemCount(myArray, 1)
console.log(items)
Something a little more generic and modern (in 2022):
import {pipe, count} from 'iter-ops';
const arr = [1, 2, 3, 5, 2, 8, 9, 2];
const n = pipe(arr, count(a => a === 2)).first; //=> 3
What's good about this:
It counts without creating a new array, so it is memory-efficient
It works the same for any Iterable and AsyncIterable
Another approach using RegExp
const list = [1, 2, 3, 5, 2, 8, 9, 2]
const d = 2;
const counter = (`${list.join()},`.match(new RegExp(`${d}\\,`, 'g')) || []).length
console.log(counter)
The Steps follows as below
Join the string using a comma Remember to append ',' after joining so as not to have incorrect values when value to be matched is at the end of the array
Match the number of occurrence of a combination between the digit and comma
Get length of matched items
I believe you can use the new Set array method of JavaScript to have unique values.
Example:
var arr = [1, 2, 3, 5, 2, 8, 9, 2]
var set = new Set(arr);
console.log(set);
// 1,2,3,5,8,9 . We get unique values as output.
You can use length property in JavaScript array:
var myarray = [];
var count = myarray.length;//return 0
myarray = [1,2];
count = myarray.length;//return 2

Categories

Resources