Javascript - elements - remove a specific element of a js array. Javascript - specific - How to remove an element from an array by value? Js remove object from array



How can I remove a specific element from an array in JavaScript? (twenty)

I have an array of integers and I am using the .push () method to add items to it.

Is there an easy way to remove a specific element from an array? Equivalent to something like array.remove (int); ,

I have to use base JavaScript - none no frames are allowed.

ES6 and No Mutation: (Oct 2016)

const removeByIndex = (list, index) => [... list.slice (0, index), ... list.slice (index + 1)];

RemoveByIndex (, 1) // =>

Edited October 2016

  • Make it simple, intuitive and explicit (https://en.wikipedia.org/wiki/Occam%27s_razor)
  • Make it unchanged (original array will remain unchanged)
  • Do it with standard JS functions if your browser doesn't support them - use polyfill

In this example code, I am using function array.filter (...) " to remove unnecessary elements from an array, this function does not change the original array and creates a new one. If your browser does not support this feature (e.g. IE prior to version 9 or Firefox prior to version 1.5), consider using polyfill filter from Mozilla .

Removing an element (ECMA-262 Edition 5 code aka oldstyle JS)

var value = 3 var arr = arr = arr.filter (function (item) (return item! == value)) console.log (arr) // [1, 2, 4, 5]

Delete item (ES2015 code)

let value = 3 let arr = arr = arr.filter (item => item! == value) console.log (arr) // [1, 2, 4, 5]

IMPORTANT ES2015 "() => ()" syntax of arrow function is not supported in IE at all, Chrome before version 45, Firefox before version 22, Safari before version 10. To use ES2015 syntax in older browsers you can use BabelJS

Removing multiple items (ES2016 code)

An added benefit of this method is that you can remove multiple items

Let forDeletion = let arr = arr = arr.filter (item =>! ForDeletion.includes (item)) // !!! Read below about array.includes (...) support !!! console.log (arr) // [1, 4]

IMPORTANT"array.includes (...)" is not supported in IE at all, Chrome prior to version 47, Firefox prior to version 43, Safari prior to version 9 and Edge prior to version 14, so

Removing multiple elements (advanced experimental JavaScript ES2018?)

// array-lib.js export function remove (... forDeletion) (return this.filter (item =>! forDeletion.includes (item))) // main.js import (remove) from "./array-lib .js "let arr = // :: 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]

Here are some ways remove element from array using javascript .

All described methods do not modify the original array and instead create a new one.

If you know the index of the element

Suppose you have an array and you want to remove the element at position i.

One way is to use slice ():

const items = ["a", "b", "c", "d", "e", "f"] const i = 3 const filteredItems = items.slice (0, i-1) .concat (items. slice (i, items.length)) console.log (filteredItems)

slice () creates a new array with the indices it receives. We simply create a new array - from the beginning 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 meaning

In this case, one good option is to use filter (), which offers more declarative an approach:

const items = ["a", "b", "c", "d", "e", "f"] const valueToRemove = "c" const filteredItems = items.filter (item => item! == valueToRemove) console.log (filteredItems)

This uses ES6 arrow functions. You can use traditional features 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 convert your ES6 code back to ES5 to make it more digestible for older browsers, but write modern JavaScript in your code.

Removing multiple items

What if you want to delete many elements instead of one element?

Let's find the simplest solution.

By index

You can simply create a function and remove items sequentially:

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 look for the 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.

You can use ES6.

Var array = ["1", "2", "3", "4", "5", "6"] var index = array.filter ((value) => value! = "3");

["1", "2", "4", "5", "6"]

You can do this easily with the filter method:

Function remove (arrOriginal, elementToRemove) (return arrOriginal.filter (function (el) (return el! == elementToRemove));) console.log (remove (, 1));

This removes all elements from the array and is also faster than the slice and indexOf combination

You should never mutate an array of an array. As this is contrary to the functional programming pattern. You can create a new array without referencing the array you want to modify using the es6 method filter;

Var myArray =;

Suppose you want to remove 5 from an 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 want to delete. So the result will be

; // 5 has been removed from this array

For further understanding, you can read the MDN documentation on Array.filter filter

If you want the new array with the positions removed, you can always remove a specific element and filter the array. It might need to extend the array object for browsers that don't implement the filtering method, but it's easier in the long run since all you do is this:

Var my_array =; delete my_array; console.log (my_array.filter (function (a) (return typeof a! == "undefined";)));

Should be displayed

If you have complex objects in an array, can you use filters? For situations where $ .inArray or array.splice is not that easy to use. Especially if the objects are possibly small in the array.

For example, if you have an object with an Id field and you want the object to be removed from the array:

This.array = this.array.filter (function (element, i) (return element.id! == idToRemove;));

Find the index of the array element you want to remove, then remove that index with splice.

The splice () method modifies the contents of an array by removing existing elements and / or adding new elements.

var array =; console.log (array) var index = array.indexOf (5); if (index> -1) (array.splice (index, 1);) // array = console.log (array);

The second splice parameter is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the removed elements.

You have 1 to 9 arrays and you want to delete 5 using the code below.

var numberArray =; var newNumberArray = numberArray.filter (m => (return m! == 5;)); console.log ("new Array, 5 removed", newNumberArray);

If you want to use multiple ex values: - 1,7,8

var numberArray =; var newNumberArray = numberArray.filter (m => (return (m! == 1) && (m! == 7) && (m! == 8);)); console.log ("new Array, 5 removed", newNumberArray);

If you want to delete an array value in ex array: -

var numberArray =; var removebleArray =; var newNumberArray = numberArray.filter (m => (return! removebleArray.includes (m);)); console.log ("new Array, removed", newNumberArray);

includes a supported browser - link

I know there are many answers already, but many of them seem to complicate the problem. Here's a simple, recursive way to delete all instances of a key - calls self until the index is found. Yes, it only works in indexOf browsers, but it is simple and can be easily populated.

Standalone function

Function removeAll (array, key) (var index = array.indexOf (key); if (index === -1) return; array.splice (index, 1); removeAll (array, key);)

Prototype method

Array.prototype.removeAll = function (key) (var index = this.indexOf (key); if (index === -1) return; this.splice (index, 1); this.removeAll (key);)

Array.prototype.removeItem = function (a) (for (i = 0; i< this.length; i++) { if (this[i] == a) { for (i2 = i; i2 < this.length - 1; i2++) { this = this; } this.length = this.length - 1 return; } } } var recentMovies = ["Iron Man", "Batman", "Superman", "Spiderman"]; recentMovies.removeItem("Superman");



How to remove an element from an array by value? (twenty)

// edited thanks to MarcoCI for advice

try this:

Function wantDelete (item, arr) (for (var i = 0; i

hope this helps you

Is there a way to remove an element from a JavaScript array?

Given the array:

Var ary = ["three", "seven", "eleven"];

I would like to do something like:

RemoveItem ("seven", ary);

I looked at splice () but that only removes the position number, whereas I need something to remove an element by its value.

Let commentsWithoutDeletedArray = commentsArray.filter ((comment) =>! (Comment.Id === commentId));

Here is a version that uses jQuery's inArray function:

Var index = $ .inArray (item, array); if (index! = -1) (array.splice (index, 1);)

You can achieve this using the function Lodash _.remove.

var array = ["three", "seven", "eleven"]; var evens = _.remove (array, function (e) (return e! == "seven";)); console.log (evens);

Const _ = require ("lodash"); _.without (, 2); // ->

Indeed, I do not understand why this cannot be solved with

Arr = arr.filter (value => value! == "seven");

Or maybe you want to use vanilla JS

Arr = arr.filter (function (value) (return value! == "seven"));

Another variant:

If (! Array.prototype.removeArr) (Array.prototype.removeArr = function (arr) (if (! Array.isArray (arr)) arr =; // let "s be nice to people who put a non-array value here .. that could be me! var that = this; if (arr.length) (var i = 0; while (i -1) (that.splice (i, 1);) else i ++; )) return that; ))

This is indexOf () inside the loop again, but assuming the array to be deleted is small relative to the array to be cleaned; each removal shortens the while loop.

This will allow you to do the following:

Var ary = ["three", "seven", "eleven"]; var aryWithoutSeven = ary.filter (function (value) (return value! = "seven")); console.log (aryWithoutSeven); // returns ["three", "eleven"]

This has also been noted in this thread somewhere else: https: //.com/a/20827100/293492

Don't use the delete option - it makes a hole in the array, as it doesn't reindex the elements after the deleted element.

> Array.prototype.remove = function (v) (... delete this ...); > var myarray = ["3", "24", "55", "2"]; undefined> myarray.remove ("55"); undefined> myarray ["3", "24", "2"]

One liner will do it

Var ary = ["three", "seven", "eleven"]; // Remove item "seven" from array var filteredAry = ary.filter (function (e) (return e! == "seven")) // => ["three", "eleven"] // In ECMA6 (arrow function syntax): var filteredAry = ary.filter (e => e! == "seven")

This is using the filter function in JS. It is supported in IE9 and up.

filter () calls the provided callback function once for each element in the array and creates a new array from all the values ​​for which the callback returns a value that evaluates to true. callback is called only for array indices that have been assigned values; it is not called for indexes that have been dropped or that have never been assigned values. Array elements that fail the callback test are simply skipped and not included in the new array.

So it's basically the same as all the other for (var key in ary) (...) solutions, except that for in is supported as IE6.

Basically the filter is a convenience method that looks much better (and is chained) as opposed to the for in constructor (AFAIK).

Check it:

For (var i in array) (if (array [i] == "seven") (array.splice (i, 1); break;))

and in the function:

Function removeItem (array, item) (for (var i in array) (if (array [i] == item) (array.splice (i, 1); break;))) removeItem (array, "seven");

Removing all matched elements from an array (not just the first one seems to be the most general answer here):

While ($ .inArray (item, array)> -1) (array.splice ($. InArray (item, array), 1);)

I've used jQuery for some hard work, but you get the idea if you want to go to your native language.

The trick is to loop through the array from start to start, so you don't mess up the indices when deleting elements.

Var deleteMe = function (arr, me) (var i = arr.length; while (i--) if (arr [i] === me) arr.splice (i, 1);) var arr = ["orange "," red "," black "," orange "," white "," orange "]; deleteMe (arr, "orange");

arr is now ["red", "black", "white"]

Function cleanArrayOfSpecificTerms (array, unwantedTermsArray) ($ .each (unwantedTermsArray, function (index, value) (var index = array.indexOf (value); if (index> -1) (array.splice (index, 1);)) ); return array;)

To use, follow these steps:

Var notInclude = ["Not", "No", "First", "Last", "Prior", "Next", "dogs", "cats"]; var splitTerms = ["call", "log", "dogs", "cats", "topic", "change", "pricing"]; cleanArrayOfSpecificTerms (splitTerms, notInclude)

I tried using the function method from jbaron above, but found that I needed to keep the original array unchanged for later use and create a new array like this:

Var newArray = referenceArray;

Function newArrRemoveItem (array, item, newArray) (for (var i = 0; i< array.length; i++) { if(array[i]!=item){ newArray.push(array[i]); } } }

Then I use it like this:

Var vesselID = record.get ("VesselID"); var otherVessels = new Array (); newArrRemoveItem (vesselArr, vesselID, otherVessels);

Now the shipArr remains intact, and every time I execute the above code, the otherVessels array includes everything but the last CAID element.

indexOf is an option, but its implementation basically searches the entire array for a value, so the runtime grows with the size of the array. (so this is in every browser, I think I only tested Firefox).

I don't have IE6 to check, but I would call it a safe bet that you can check at least a million array elements per second this way on almost any client machine. If [array size] * [searches per second] could grow over a million, you should consider another implementation.

Basically you can use an object to create an index for your array, for example:

Var index = ("three": 0, "seven": 1, "eleven": 2);

Any normal JavaScript framework will create a search index for such objects so that you can quickly translate a key to a value, no matter how many properties the object has.

This is just a basic method, depending on your needs, you can combine multiple objects and / or arrays to make the same data quickly searchable for different properties. If you provide your specific needs, I can suggest a more specific data structure.

// This function allows remove even array from array var removeFromArr = function (arr, elem) (var i, len = arr.length, new_arr =, sort_fn = function (a, b) (return a - b;); for ( i = 0; i< len; i += 1) { if (typeof elem === "object" && typeof arr[i] === "object") { if (arr[i].toString() === elem.toString()) { continue; } else { if (arr[i].sort(sort_fn).toString() === elem.sort(sort_fn).toString()) { continue; } } } if (arr[i] !== elem) { new_arr.push(arr[i]); } } return new_arr; }

Usage example

Var arr =, "abc", 1, "1", 1]; removeFromArr (arr, 1); // ["2",, "abc", "1"] var arr = [, 2, "a",,]; removeFromArr (arr,); //]

Let arr =; console.log (arr); // result let index = arr.indexOf (30); if (index> -1) (arr.splice (index, 1);) console.log (arr); // result

Var index = array.indexOf ("item"); if (index! = - 1) (array.splice (index, 1);)

shift

Use .shift to remove the first element of the array.

For example:

Var array =; array.shift ();

array results in:

For example:

Var array =; array.pop ();

array results in:

Both methods return the removed item;

splice

Use.splice () to remove a series of elements from an array. .splice () takes two parameters, a starting index and an optional cardinality to remove. If the second parameter is not, splice () will remove all elements from the starting index through the end of the array.

For example:

Var array =; array.splice (1, 2);

leaves an array containing:

The return of array.splice () is a new array containing the removed elements. In the above example, the return would be:

Thus, omitting the second parameter effectively splits the array into two arrays with the original ending up to the specified index:

Var array =; array.splice (2);

Leaves an array containing and returns.

delete

Use delete to remove an element from an array without changing the length of the array:

Var array =; console.log (array.length); // 5 delete array; console.log (array); // console.log (array.length); // 5

Array.prototype.length

Assigning the value to the length of the array changes the length by the specified value. If the new value is less than the length of the array, elements will be removed from the end of the value.

Array =; array.length = 2; console.log (array); //

I have described only a part of the methods for working with arrays.

Here we will talk about adding, removing array elements. About inverting and sorting an array, as well as slicing, replacing and combining arrays.

Adding elements to an array.

You can use the length property to add new elements to the array:

Var myArray = ["Apple", "Microsoft", "Google", "Facebook"]; myArray = "Yahoo!"; console.log (myArray); // ["Apple", "Microsoft", "Google", "Facebook", "Yahoo!"]

This will work because array elements are numbered from zero, and length one more. Length always equivalent index + 1 so it is very easy to add a new element to the end of the array. Strange, but you can add an element at a position that is much larger than the length of the array itself:

Var myArray = ["Jimi Hendrix", "Eric Clapton", "Jimmy Page", "Keith Richards"]; myArray = "Lindsey Buckingham"; console.log (myArray); // ["Jimi Hendrix", "Eric Clapton", "Jimmy Page", "Keith Richards", undefined × 95, "Lindsey Buckingham"] console.log (myArray.length); // 100

As shown in the comments, 95 empty slots and a "Lindsey Buckingham" element will be added to the end of the array. After that, we get the length 100. Another way to add a new element to the array is to use the method push ():

Var myArray = ["Paul McCartney", "John Lennon", "George Harrison"]; myArray.push ("Ringo Starr", "George Martin"); console.log (myArray); // ["Paul McCartney", "John Lennon", "George Harrison", "Ringo Starr", "George Martin"]

Method push () always returns the new length of the array (in our case 5). You can add an item using splice ():

Var myArray = ["acorn", "beech", "mongongo", "macadamia"]; myArray.splice (2, 0, "cashew"); // adds "cashew" into index 2 console.log (myArray); // ["acorn", "beech", "cashew", "mongongo", "macadamia"]

When the second argument is 0, it means that no element will be removed, and therefore any subsequent arguments will be added to the array at the position specified in the first argument.

Removing elements from an array

Removing an element is a little more difficult than adding it. To remove an element from the end of an array, one can use pop ():

Var myArray = ["7-up", "Sprite", "Ginger Ale", "Lemonade"]; myArray.pop (); console.log (myArray); // ["7-up", "Sprite", "Ginger Ale"]

Method pop () always removes the last element in the array and returns it.

You can also use splice () method:

Var myArray = ["cassava", "nutmeg", "lupin", "rhubarb"]; myArray.splice (2, 1); // remove element at index 2 console.log (myArray); // ["cassava", "nutmeg", "rhubarb"]

Unlike the method splice (), which is used to add elements, here the second argument is 1, which says that we want to remove the element with index 2 (or 3rd in a row). In this case, the "lupin" element has been removed.

You can remove an element of an array using the operator delete:

Var myArray = ["Byte Bandit", "Eliza", "Jeefo", "Michelangelo"]; console.log (myArray.length); // 4 delete myArray; // remove Eliza console.log (myArray.length); // 4 console.log (myArray); // ["Byte Bandit", undefined × 1, "Jeefo", "Michelangelo"]

First important note: delete () does not change the length of the array after the element is removed (even if it was the last element in the array). Second: delete () changes the value of the removed element to undefined, so when reversing myArray = undefined.

A good way to remove an element from an array is to use John Resig's Array.remove. Below is a usage example taken from his page:

// 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); }; // Удаление 2 элемента из массива array.remove(1); // Удаление 2-ого элемента с конца массива array.remove(-2); // Удаление второго и третьего элемента array.remove(1,2); // Удаление последнего и предпоследнего элемента array.remove(-2,-1);

You might want to look at the solution by Viral Patel, one of the functions in Underscore.js, or jQuery's grep ().

Additionally, in JavaScript there is a method shift (), which removes the first element in the array and returns its value. Let's see the code:

Var myArray = ["Matt Kramer", "Jason Bieler", "Tom Defile", "Phil Varone"]; console.log (myArray.length); // 4 var firstItem = myArray.shift (); console.log (firstItem); // Matt Kramer console.log (myArray.length); // 3 console.log (myArray); // ["Jason Bieler", "Tom Defile", "Phil Varone"]

Using the method shift () we removed the item, but saved its value in our firstItem variable. The length of the array has changed from 4 to 3.

This method can be useful in conjunction with the method push (). By using them together, we can efficiently queue up the elements in an array. We keep the length of the array by removing an element from the beginning and adding a new one to the end.

On the contrary, we can use the method unshift () to add an element to the beginning of the array:

Var myArray = ["apito", "castanets", "maraca"]; console.log (myArray.length); // 3 myArray.unshift ("chime bar", "tan-tan"); console.log (myArray.length); // 5 console.log (myArray); // ["chime bar", "tan-tan", "apito", "castanets", "maraca"]

Using the method unshift () with method pop (), you can queue backwards by adding elements to the beginning and removing from the end of the array.

Reversal and sorting of array elements.

To flip the elements in an array, we can use reverse ():

Var myArray = ["countdown", "final", "the"]; console.log (myArray); // ["countdown", "final", "the"] myArray = myArray.reverse (); console.log (myArray); // ["the", "final", "countdown"]

Sort array elements into alphabetical order possibly using the method sort ():

Var myArray = ["xylophones", "zebras", "juggernauts", "avocados"]; console.log (myArray); // ["xylophones", "zebras", "juggernauts", "avocados"] myArray = myArray.sort (); console.log (myArray); // ["avocados", "juggernauts", "xylophones", "zebras"]

But that won't work with numbers.

Var myArray =; console.log (myArray); // myArray = myArray.sort (); console.log (myArray); //

If you need to sort the numbers, then you can use the following code:

Function compareNumbers (a, b) (return a - b;) var myArray =; console.log (myArray); // myArray = myArray.sort (compareNumbers); console.log (myArray); //

As shown above with a simple function pasted in sort (), the array containing the numbers will be sorted correctly.

Combining arrays.

You can concatenate 2 or more arrays and get 1 array that contains the elements of the concatenated arrays. For this we use the method concat ():

Var myArray = ["Jay Ferguson", "Andrew Scott"]; var myArray2 = ["Chris Murphy", "Patrick Pentland"]; var myNewArray = myArray.concat (myArray2); console.log (myNewArray); // ["Jay Ferguson", "Andrew Scott", "Chris Murphy", "Patrick Pentland"]

Var myArray = ["Jay Ferguson", "Andrew Scott"]; var myNewArray = myArray.concat ("Chris Murphy", "Patrick Pentland"); console.log (myNewArray); // ["Jay Ferguson", "Andrew Scott", "Chris Murphy", "Patrick Pentland"]

Splitting an array.

You can create a new array containing 1 or more elements from an existing array using the function slice ():

Var myArray = ["Vocals", "Bass", "Guitar", "Drums", "Apples", "Oranges"]; var myNewArray = myArray.slice (4); console.log (myNewArray); // ["Apples", "Oranges"]

Method slice () takes 1 or 2 arguments. If 1 argument (index) is passed, then a new array is created from all elements of the old one, starting from the given index. If 2 arguments are passed, then a new array is created from the elements starting from the first argument and up to the element at the index passed in the second parameter, not including the last one. To make it clearer, let's see the code below:

Var myArray = ["Vocals", "Bass", "Guitar", "Drums", "Apples", "Oranges"]; var myNewArray = myArray.slice (0, 4); console.log (myNewArray); // ["Vocals", "Bass", "Guitar", "Drums"]

Replacing elements in an array.

We use splice () to remove elements from an array, but we can also replace an element in an array with new elements:

Var myArray = ["Rivers Cuomo", "Patrick Wilson", "Brian Bell", "Matt Sharp"]; myArray.splice (3, 1, "Scott Shriner"); // replace 1 element with index 3 console.log (myArray); // ["Rivers Cuomo", "Patrick Wilson", "Brian Bell", "Scott Shriner"]

Method splice () always returns an array containing the elements that have been removed. Line 2 will return 1 item "Brian Bell".

Conclusion

These articles have described methods for working with arrays in JavaScript. Some additional elements can be viewed on MDN that I have not included in this post. They only work in IE9 +, so they might not be useful.

Anything to add? Or do you know any interesting library that will help you manage arrays? Please comment!