Javascript - remove - js arrays. How to remove a specific element of a JavaScript array? remove element from javascript array

💖 Like it? Share the link with your friends

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

Here we will talk about adding, removing array elements. About flipping 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 an 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 is one more. Length is always equivalent to index + 1 , so it's very easy to add a new element to the end of the array. Strangely, 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 will be added and the element "Lindsey Buckingham" will be added to the end of the array. After that, we get a length of 100. Another way to add a new element to an array is to use the push() method:

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

The push() method always returns the new length of the array (5 in our case). You can add an element 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, this 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, pop() can be used:

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

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

You can also use the 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 splice() method, which is used to add elements, here the second argument is 1, which says that we want to remove the element at index 2 (or 3rd in a row). In this case, the "lupin" element has been removed.

You can delete an array element using the delete operator:

Var myArray = ["Byte Bandit", "Eliza", "Jeefo", "Michelangelo"]; console.log(myArray.length); // 4 delete myArray; // delete 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 an array after an element is removed (even if it was the last element in the array). Second, delete() changes the value of the element being deleted to undefined, so myArray = undefined when accessed.

A good way to remove an element from an array is to use John Resig's Array.remove . Below is an example of usage 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, JavaScript has a shift() method that removes the first element in an 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"]

With the shift() method, we removed the item, but stored 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 push() method. By using them together, we can effectively queue up the elements in an array. We store the length of an array by removing an element from the beginning and adding a new one to the end.

Conversely, we can use the unshift() method to add an element to the beginning of an 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"]

By using the unshift() method with the pop() method, you can create queues in reverse side, adding elements to the beginning and removing from the end of the array.

Flipping and sorting array elements.

To reverse 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"]

It is possible to sort the elements of an array in alphabetical order using the sort() method:

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

But it won't work with numbers.

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

If you need to sort numbers, 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 inserted into sort(), an array containing numbers will be sorted correctly.

Union of arrays.

We can merge 2 or more arrays and get 1 array that contains the elements of the joined arrays. To do this, we use the concat() method:

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.

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

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

The slice() method 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 given, then a new array is created from the elements starting from the first argument and up to the element with 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 at index 3 console.log(myArray); // ["Rivers Cuomo", "Patrick Wilson", "Brian Bell", "Scott Shriner"]

The splice() method 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. There are some additional items on MDN that I didn't include in this post. They only work in IE9+, so they might not be useful.

Have something to add? Or do you know some interesting library that will help you manage arrays? Comment please!

There are several ways to remove an element from an array in JavaScript. These include the pop and shift methods. The pop method removes the first element from the given array. The shift method removes the last element from the given array.

You can set the array length to 0 if you want to remove all elements from the given array. But what, do you need to remove a certain element?

For example:

Array_name.splice(index);

Array_name.delete

You can use the splice method. It returns a new array of removed elements. And the original array contains the remaining elements.

Check out the demo below to learn how to use the JavaScript splice method and other ways to remove certain elements.

Demonstration of removing a specific element using the splice method

This demo creates an array of numbers. Initially, five elements are added to the array. The splice method is then used to remove the third element. Similarly, in JavaScript, you can remove the first element of an array.

Numeric array elements displayed before and after use JavaScript method splice like this:

JavaScript code with splice method:


"; for (i=0; i< Arr_Numbers.length; i++){ the_arr_before_after += Arr_Numbers[i] + "
"; ) document.getElementById("p1").innerHTML = the_arr_before_after; Arrretrun = Arr_Numbers.splice(2,1); var the_arr_before_after = "Array elements after splice method:
"; for (i=0; i< Arr_Numbers.length; i++){ the_arr_before_after += Arr_Numbers[i] + "

You may have noticed that I used two parameters for the JavaScript to remove an array element. The first specifies the index of the element to be removed. The second is how many elements to remove after the specified key.

The following demo shows the case where we use the second parameter.

What if the second parameter is not specified in the JavaScript splice method?

Using the same code but without the second parameter in the splice method:

Arr_Numbers.splice(2);

Code and result:

View online demo and code

As you can see, all elements before the specified index number have been removed here as well. In addition, the splice method returns an array of removed elements.

JavaScript code:

var Arr_Numbers = ; var i; var the_arr_before_after = "The original array:
"; for (i=0; i< Arr_Numbers.length; i++){ the_arr_before_after += Arr_Numbers[i] + "
"; ) document.getElementById("p1").innerHTML = the_arr_before_after; Arrretrun = Arr_Numbers.splice(2); var the_arr_before_after = "Array elements after splice method:
"; for (i=0; i< Arr_Numbers.length; i++){ the_arr_before_after += Arr_Numbers[i] + "
"; ) document.getElementById("p2").innerHTML = the_arr_before_after; //The removed array elements in the returned array var the_arr_before_after = "The removed array elements:
"; for (i=0; i< Arrretrun.length; i++){ the_arr_before_after += Arrretrun[i] + "
"; ) document.getElementById("p3").innerHTML = the_arr_before_after;

Using the delete function to remove an array element

You can also use the delete function to remove an element from an array in JavaScript. But it saves empty space, and if you return this array after using the function, then the removed element will be displayed as undefined .

Consider a demo that uses the delete function:

View online demo and code

JavaScript code:

var Arr_Strings = ["The","JavaScript","Array","Totorial"]; var i; var the_arr_before_after = "The original string array elements:

"; for (i=0; i< Arr_Strings.length; i++){ the_arr_before_after += Arr_Strings[i] + "
"; ) document.getElementById("p1").innerHTML = the_arr_before_after; //Using the delete function delete Arr_Strings; var the_arr_before_after = "Array elements after splice method:

"; for (i=0; i< Arr_Strings.length; i++){ the_arr_before_after += Arr_Strings[i] + "
"; ) document.getElementById("p2").innerHTML = the_arr_before_after;

You can see that the third element is rendered undefined after it has been removed with the delete function.



remove specific element of js array(20)

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

Given an array:

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

I would like to do something like:

RemoveItem("seven", ary);

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

// edited thanks to MarcoCI for the advice

try it:

Function wantDelete(item, arr)( for (var i=0;i !(comment.Id === commentId));

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

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

You can achieve this using Lodash's _.remove function.

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

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

Indeed, I don't understand why this can't 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; ) )

It's indexOf() inside the loop again, but assuming the array to remove is small relative to the array to be cleared; each deletion 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 was also noted in this thread somewhere else: https://.com/a/20827100/293492

Don't use the delete option - it makes a hole in the array since 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 uses the filter function in JS. It is supported in IE9 and above.

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

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

Basically, a filter is a convenience method that looks much nicer (and is chainable) as opposed to a 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 matching 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 used jQuery for the hard work, but you get the idea if you want to go native.

The trick is to go through the array from start to start so you don't mess up the indexes when you remove 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 need to keep the original array intact 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 vesselArr remains intact, and every time I execute the above code, the otherVessels array includes all but the last CAID element.

indexOf is an option, but its implementation basically searches the entire array for the value, so the execution time grows with the size of the array. (so it's in every browser, I guess, I only checked Firefox).

I don't have IE6 to check, but I'd 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] * [ search terms per second] can grow to more than a million, you should consider a different implementation.

Basically you can use an object to create an index for your array like so:

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

Any normal JavaScript environment will create a lookup index for such objects so you can quickly translate a key into a value, no matter how many properties the object has.

This is just a basic method, depending on your needs, you can concatenate multiple objects and/or arrays to make the same data quickly searchable for different properties. If you specify 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); )

The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.

The source for this interactive example is stored in a GitHub repository. If you"d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax delete expression

Any variable defined with var is marked as non-configurable. In the following example, salary is non-configurable and cannot be deleted. In non-strict mode, the delete operation will return false .

Function Employee() ( delete salary; var salary; ) Employee();

Let's see how the same code behaves in strict mode. Instead of returning false , the statement raises a SyntaxError .

"use strict"; function Employee() ( delete salary; // SyntaxError var salary; ) // Similarly, any direct access to a function // with delete will raise a SyntaxError function DemoFunction() ( //some code ) delete DemoFunction; // SyntaxError

Examples // Creates the property adminName on the global scope. adminName="xyz"; // Creates the property empCount on the global scope. // Since we are using var, this is marked as non-configurable. The same is true of let and const. var empCount = 43; EmployeeDetails = ( name: "xyz", age: 5, designation: "Developer" ); // adminName is a property of the global scope. // It can be deleted since it is created without var, // and is therefore configurable. delete adminName; // returns true // On the contrary, empCount is not configurable // since var was used. delete empCount; // returns false // delete can be used to remove properties from objects. delete EmployeeDetails.name; // returns true // Even when the property does not exist, delete returns "true". delete EmployeeDetails.salary; // returns true // delete does not affect built-in static properties. delete Math.PI; // returns false // EmployeeDetails is a property of the global scope. // Since it was defined without "var", it is marked configurable. delete EmployeeDetails; // returns true function f() ( var z = 44; // delete doesn't affect local variable names delete z; // returns false ) delete and the prototype chain

In the following example, we delete an own property of an object while a property with the same name is available on the prototype chain:

Function Foo() ( this.bar = 10; ) Foo.prototype.bar = 42; varfoo = new Foo(); // foo.bar is associated with the // own property. console.log(foo.bar); // 10 // Delete the own property within the // foo object. delete foo.bar; // returns true // foo.bar is still available in the // prototype chain. console.log(foo.bar); // 42 // Delete the property on the prototype. delete Foo.prototype.bar; // returns true // The "bar" property can no longer be // inherited from Foo since it has been // deleted. console.log(foo.bar); // undefined

deleting array elements

When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees are removed with delete .

Var trees = ["redwood", "bay", "cedar", "oak", "maple"]; delete trees; if (3 in trees) ( // this is not executed )

If you want an array element to exist but have an undefined value, use the undefined value instead of the delete operator. In the following example, trees is assigned the value undefined, but the array element still exists:

Var trees = ["redwood", "bay", "cedar", "oak", "maple"]; trees = undefined; if (3 in trees) ( // this is executed )

If instead, you want to remove an array element by changing the contents of the array, use the splice method. In the following example, trees are removed from the array completely using splice :

Var trees = ["redwood", "bay", "cedar", "oak", "maple"]; trees splice(3,1); console log(trees); // ["redwood", "bay", "cedar", "maple"]

Specifications Specification Status Comment
ECMAScript Latest Draft (ECMA-262)
Draft
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of "The delete Operator" in that specification.
standard
ECMAScript 5.1 (ECMA-262)
The definition of "The delete Operator" in that specification.
standard
ECMAScript 1st Edition (ECMA-262)
The definition of "The delete Operator" in that specification.
standard initial definition. Implemented in JavaScript 1.2.
Browser compatibility

The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.jsdelete
Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 4Opera Full support YesSafari Full support YesWebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 1.0nodejs Full support Yes
Legend Full support Full support Cross-browser notes

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.



How to remove a specific element from an array in JavaScript? (20)

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

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

I have to use base javascript- none frames are not allowed.

ES6 and no mutation: (Oct 2016) const removeByIndex = (list, index) => [ ...list.slice(0, index), ...list.slice(index + 1) ];

RemoveByIndex(,1) //=>

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

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

Deleting an item (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 ] Remove item (ES2015 code) let value = 3 let arr = arr = arr.filter(item => item !== value) console.log(arr) // [ 1, 2, 4, 5 ]

IMPORTANT ES2015 "() => ()" arrow function syntax 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 elements (ES2016 code)

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

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 before version 47, Firefox before version 43, Safari before version 9 and Edge before version 14, so

Deleting multiple items (Best 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 to remove an element from an array with JavaScript.

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

If you know the element index

Let's say 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 the 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 the ES6 code back to ES5 to make it more readable for older browsers, but write modern JavaScript in your code.

Deleting multiple items

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

Let's find the simplest solution.

By index

You can just create a function and remove elements 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 an include inside a 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 combination of slice and indexOf

You should never mutate an array of an array. Because it goes against the functional programming pattern. You can create a new array without referencing the array you want to change using the es6 method filter;

Var myArray = ;

Let's say you want to remove 5 from an array, you can just do it like this.

MyArray = myArray.filter(value => value !== 5);

This will give you a new array without the value you want to remove. 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 the specific element and filter the array. It might need to extend the array object for browsers that don't implement the filter 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";)));

Must be displayed

If you have complex objects in an array, can you use filters? In situations where $.inArray or array.splice are not that easy to use. Especially if the objects are perhaps 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 parameter to splice 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 want to remove 5 using below code.

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

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

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

If you want to remove array value in array ex:-

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

includes supported browser - link

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

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



tell friends