the Internet Windows Android

JQuery Delete an array element by value. How to delete a specific JavaScript array element? Using the Delete function to remove an array element

shift

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

For example:

Var array \u003d; array.shift ();

the array leads to:

For example:

Var array \u003d; array.pop ();

the array leads to:

Both methods return a remote element;

splice

Use.splice () To remove a number of elements from the array. .splice () takes two parameters, an initial index and an optional number of elements to remove. If the second parameter is not.splice () deletes all elements from the initial index through the end of the array.

For example:

Var array \u003d; array.splice (1, 2);

leaves array comprising:

Return array.splice () is a new array containing remote items. In the example above, the refund will be as follows:

Thus, lowering the second parameter effectively breaks the array into two array with the initial end to the specified index:

Var array \u003d; array.splice (2);

Leaves Array containing and returns.

delete

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

Var array \u003d; Console.log (Array.Length); // 5 Delete Array; Console.log (Array); // Console.log (Array.Length); // five

Array.prototype.Length.

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

Array \u003d; array.length \u003d 2; Console.log (Array); //

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 \u003d "xyz"; // Creates The Property Empcount on The Global Scope. // SINCE WE A USING VAR, THIS IS MARKED AS NON-CONFIGURABLE. The Same IS True of Let and Const. var empcount \u003d 43; EmployeEedetails \u003d (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 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 EmployeEedetails.salary; // Returns True // Delete Does Not Affect Built-in Static Properties. DELETE MATH.PI; // RETURNS FALSE // EmployeEedetails Is A Property of the Global Scope. // SINCE IT WAS DEFINED WITHOUT "VAR", IT IS MARKED CONFIGURABLE. Delete EmployeEedetails; // RETURNS TRUE FUNCTION F () (VAR Z \u003d 44; // DELETE DOESN "T AFFECT LOCAL VARIABLE NAMES DELETE Z; // RETURNS FALSE)

dELETE AND THE PROTOTYPE CHAIN

In The Following Examplesis, 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 \u003d 10;) foo.prototype.bar \u003d 42; var foo \u003d 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 Is Removed with Delete.

Var Trees \u003d ["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 \u003d ["Redwood", "Bay", "Cedar", "Oak", "Maple"]; Trees \u003d 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 Is Removed from the Array Completely Using SPLICE:

Var Trees \u003d ["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.MobileServer
Chrome.Edge.Firefox.Internet Explorer.Opera.Safari.Android WebView.Chrome for AndroidFirefox for AndroidOpera for AndroidSafari On ios.Samsung internetNode.js.
delete.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 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 PROPERTY, SOME CONFUSING BEHAVIOR RESULTS, PREVENTING OTHER BROWSER 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 Will Be Iterated In Its With The Same Name old. Position - Not At The End of the Iteration Sequence As One Might Expect After Having Deleted The Property and then Added It Back.

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

Here we will talk about adding, removing the elements of the array. On turning and sorting the array, as well as about cutting, replacing and combining arrays.

Adding elements to an array.

You can use the Length property to add new items to an array:

Var Myarray \u003d ["Apple", "Microsoft", "Google", "Facebook"]; myarray \u003d "Yahoo!"; Console.log (Myarray); // [Apple, "Microsoft", "Google", "Facebook", "Yahoo!"]

It will work, because The elements of the array are numbered from scratch, and length. per unit more. Length. Always equivalent index + 1.So it's very easy to add a new element to the end of the array. Strange, but you can add an item to a position that is much larger than the length of the array itself:

VAR MYARRAY \u003d ["Jimi Hendrix", "Eric Clapton", "Jimmy Page", "Keith Richards"]; myarray \u003d "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 the element "Lindsey Buckingham" will be added to the end of the array. After that, we will get a length of 100. Another way to add a new element to an array is to use the method push ():

Var Myarray \u003d ["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 a new length of the array (in our case 5). You can add an item using sPLICE ():

Var Myarray \u003d ["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 0, this means that no item will be removed, and therefore any subsequent arguments will be added to the array to the position specified in the first argument.

Removal of elements from the array

Remove the element is slightly more complicated than add it. To remove an element from the end of the array, you can use pOP ():

Var Myarray \u003d ["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 \u003d ["Cassava", "Nutmeg", "Lupin", "Rhubarb"]; myarray.splice (2, 1); // Delete an element with an index 2 Console.log (Myarray); // ["CassaVa", "Nutmeg", "Rhubarb"]

In contrast to the method sPLICE (), which is used to add items, here the second argument is 1, which says that we want to remove an element with an index 2 (or 3rd account). In this case, the element "Lupin" retired.

You can delete an array element using the operator delete:

Var myarray \u003d ["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"]

The first important note: delete () Does not change the length of the array after removing the element (even if it was the last element in the array). Second: delete () Changes the value of the removed item on undefined, so when contacting myarray \u003d undefined..

A good way to remove an element from the array - use John Resig's Array.Remove. Below an example of using, taken from its page:

// Array Remove - by John Resig (Mit Licensed) Array.prototype.Remove \u003d Function (from, to) (VAR REST \u003d THIS.Slice ((To || From) + 1 || this.length); this.lengthth \u003d 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 may want to see the decision by Viral Patel, one of the functions in Underscore.js, or jQuery's grep ().

Advanced, B. 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 \u003d ["MATT KRAMER", "Jason Bieler", "Tom Defile", "Phil Varone"]; Console.log (Myarray.Length); // 4 var firstitem \u003d 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 have deleted 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 together with the method. push (). Using them together, we can effectively build a queue of elements in the array. We retain the length of the array by removing the 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 \u003d ["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 a method pop () You can create queue in the opposite direction by adding elements to the beginning and removing from the end of the array.

Turning and sorting the elements of the array.

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

Var Myarray \u003d ["Countdown", "Final", "The"]; Console.log (Myarray); // ["Countdown", "Final", "The"] MYARRAY \u003d MYARRAY.REVERSE (); Console.log (Myarray); // ["The", "Final", "Countdown"]

Sort the elements of the array in alphabetical order maybe using the method sort ():

Var ryarray \u003d ["xylophones", "zebraras", "juggernauts", "avocados"]; Console.log (Myarray); // ["xylophones", "zebras", "juggernauts", "avocados"] myarray \u003d myarray.sort (); Console.log (Myarray); // ["Avocados", "juggernauts", "xylophones", "zebras"]

But it will not work with numbers.

Var myarray \u003d; Console.log (Myarray); // myarray \u003d myarray.sort (); Console.log (Myarray); //

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

FUNCTION COMPARENUBERS (A, B) (RETURN A - B;) VAR MYARRAY \u003d; Console.log (Myarray); // Myarray \u003d Myarray.Sort (Comparenumbers); Console.log (Myarray); //

As shown above, using a simple function inserted into sort () An array containing numbers will be sorted correctly.

Combining arrays.

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

Var Myarray \u003d ["Jay Ferguson", "Andrew Scott"]; Var Myarray2 \u003d ["Chris Murphy", "Patrick Pentland"]; var mynewarray \u003d ryarray.concat (myarray2); Console.log (MYNEWARRAY); // ["Jay Ferguson", "Andrew Scott", "Chris Murphy", "Patrick Pentland"]

Var Myarray \u003d ["Jay Ferguson", "Andrew Scott"]; var mynewarray \u003d ryarray.concat ("Chris Murphy", "Patrick Pentland"); Console.log (MYNEWARRAY); // ["Jay Ferguson", "Andrew Scott", "Chris Murphy", "Patrick Pentland"]

Separation of the array.

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

Var myarray \u003d ["vocals", "bass", "guitar", "drums", "apples", "oranges"]; var mynewarray \u003d myarray.slice (4); Console.log (MYNEWARRAY); // ["Apples", "Oranges"]

Method slice () Takes 1 or 2 arguments. If 1 argument is transferred (index), then the new array is created from all elements of the old, starting from this index. If there are 2 arguments, the new array is created from the elements, starting from the first argument to the element with the index transmitted in the second parameter, not including the latter. To be clearer, let's see the code below:

Var myarray \u003d ["vocals", "bass", "guitar", "drums", "apples", "oranges"]; var mynewarray \u003d myarray.slice (0, 4); Console.log (MYNEWARRAY); // ["Vocals", "Bass", "Guitar", "Drums"]

Replacing elements in the array.

We use sPLICE () To remove elements from the array, but we can also replace the element in the array for new items:

Var Myarray \u003d ["Rivers Cuomo", "Patrick Wilson", "Brian Bell", "Matt Sharp"]; myarray.splice (3, 1, "Scott Shriner"); // Replace 1 element with an index 3 Console.log (Myarray); // ["Rivers Cuomo", "Patrick Wilson", "Brian Bell", "Scott Shriner"]

Method sPLICE () Always return an array containing elements that have been deleted. In the line 2 will be returned 1 element "Brian bell".

Conclusion

These articles described how to work with arrays in JavaScript. Some additional items can be viewed on the MDN, which I did not include in this post. They work only in IE9 +, so they can be useless.

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



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

// has been edited by marcoci for advice

try this:

Function WantDelete (Item, Arr) (for (VAR i \u003d 0; I

i hope this will help you

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

Given the array:

Var Ary \u003d ["Three", "Seven", "Eleven"];

I would like to do something like:

RemoveItemm ("Seven", ARY);

I viewed Splice () But it only deletes the position number, whereas I need something to remove the item by its value.

Let CommentsWithoutDeledArray \u003d Commentsarray.Filter ((Comment) \u003d\u003e! (Comment.id \u003d\u003d\u003d commentid));

Here is the version in which the Inarray JQuery function is used:

Var index \u003d $ .inarray (Item, Array); if (index! \u003d -1) (array.splice (index, 1);)

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

var Array \u003d ["Three", "Seven", "Eleven"]; var evens \u003d _.remove (Array, Function (E) (RETURN E! \u003d\u003d "SEVEN";)); Console.log (EVENS);

Const _ \u003d Require ("Lodash"); _.without (, 2); // -\u003e

Indeed, I do not understand why it is impossible to solve with

Arr \u003d Arr.Filter (Value \u003d\u003e Value! \u003d\u003d "Seven");

Or maybe you want to use Vanilla JS

Arr \u003d Arr.Filter (Return Value! \u003d\u003d "Seven"));

Another variant:

If (! Array.prototype.removearr) (array.prototype.removearr \u003d function (ARR) (if (! Array.isarray (arr)) arr \u003d; // let "s be nice to people WH PUT A NON-ARRAY VALUE Here .. that Could Be Me! var than \u003d this; if (arr.length) (var i \u003d 0; while (I -1) (that.splice (I, 1);) ELSE I ++; )) Return that; ))

This indexof () inside the cycle is again, but under the assumption that an array for removal is small relative to the array that needs to be cleaned; Each removal reduces the While cycle.

This will allow you to do the following:

Var Ary \u003d ["Three", "Seven", "Eleven"]; Var Arywithoutseven \u003d Ary.Filter (Return Value! \u003d "Seven")); Console.log (ARYWITHOUTSEVEN); // Returns ["Three", "Eleven"]

It was also noted in this thread somewhere else: https: //.com/a/293492

Do not use the option with Delete - it makes a hole in the array, since it does not reinperse the elements after the remote element.

\u003e Array.prototype.Remove \u003d Function (V) (... Delete this ...); \u003e Var Myarray \u003d ["3", "24", "55", "2"]; undefined\u003e myarray.remove ("55"); undefined\u003e myarray ["3", "24", "2"]

One liner will do it

Var Ary \u003d ["Three", "Seven", "Eleven"]; // Remove Item "Seven" from Array Var FiltereDary \u003d ARY.FILTER (FUNCTION (E) (Return E! \u003d\u003d "Seven")) // \u003d\u003e ["Three", "Eleven"] // in ECMA6 (arrow Function Syntax): var filteredary \u003d Ary.Filter (E \u003d\u003e E! \u003d\u003d "SEVEN")

This uses the Filter function in JS. It is supported in IE9 and higher.

filter () causes the reverse call feature once for each element in the array and creates a new array of all values \u200b\u200bfor which the callback returns a value that leads to the true one. Callback is called only for array indices, which are assigned values; It is not called for indexes that have been deleted or who have never been assigned to values. An array elements that do not pass a callback test are simply skipped and not included in a new array.

Thus, mostly, this is the same as everyone else for (VAR KEY in ARY) (...) solutions, except that the for in is supported as IE6.

In principle, the filter is a method of convenience that looks much better (and is chain), unlike the for in (AFAIK) designer.

Check this:

For (Var i in Array) (if (Array [i] \u003d\u003d "Seven") (array.splice (I, 1); Break;))

and in the function:

FUNCTION REMOVEIEM (Array, Item) (IF (Array [i] \u003d\u003d Item) (Array.splice (I, 1); Break;))) RemoveItem (Array, "SEVEN");

Removing all matching elements from the array (and not just the first, as it seems the most common answer here):

While ($ .inarray (Item, Array)\u003e -1) (Array.splice ($. Inarray (Item, Array), 1);)

I used jQuery for hard work, but you understood whether you want to go to your native language.

The trick is to go through an array from the beginning before the start, so you will not spoil the indexes when removing the items.

Var deleteme \u003d function (arr, me) (var i \u003d arr.length; while (i--) if (arr [i] \u003d\u003d\u003d me) arr.splice (i, 1);) var arr \u003d ["Orange "," Red "," Black "," Orange "," White "," Orange "]; DELETEME (ARR, "ORANGE");

arr Now ["Red", "Black", "White"]

FUNCTION CLEANARRAYOFSPECIFICTERMS (ARRAY, UNWANEDTERMSARRAY) ($ .EACH (UnwantedtermsArray, Function (Index, Value) (Value); ifex (index\u003e -1) (array.splice (index, 1);)) ); Return Array;)

To use, follow these steps:

Var notinclude \u003d ["Not", "No", "First", "Last", "Prior", "Next", "Dogs", "Cats"]; var splitterms \u003d ["Call", "Log", "Dogs", "Cats", "Topic", "Change", "Pricing"]; CleanarrayOfSpecificterms (Splitterms, Notinclude)

I tried to use the method of function from Jbaron above, but I found that I need to save the original array without changes to use later and create a new array as follows:

Var newarray \u003d referenceArray;

FUNCTION NEWARRREMOVEIEM (Array, Item, Newarray) (for (Var i \u003d 0; I< array.length; i++) { if(array[i]!=item){ newArray.push(array[i]); } } }

Then I use it like this:

Var vselid \u003d record.get ("VesselID"); VAR OtherVessels \u003d New Array (); NewARRREMOVEIEM (Vesselrr, VesselID, OtherVessels);

Now the shiparr remains intact, and every time I perform the above code, the OtherVessels array includes everything except the last Caid element.

indexof is an option, but its implementation is mainly looking for the entire array for meaning, so the execution time grows with the size of the array. (So \u200b\u200bthis is in every browser, I think I only checked Firefox).

I do not have an IE6 for checking, but I would call it a safe bid that you can check at least a million elements of the array per second thus practically on any client machine. If [the size of the array] * [Search queries per second] can grow more than a million, you should consider another implementation.

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

Var Index \u003d ("Three": 0, "Seven": 1, "Eleven": 2);

Any Normal JavaScript environment will create a search index for such objects so that you can quickly translate the key to value, regardless of how many properties has an object.

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

// This Function Allows Remove Even Array from Array Var RemoveFromArr \u003d Function (Arr.Length, new_arr \u003d, sort_fn \u003d function (A, B) (Return A - B;); for ( i \u003d 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; }

Example of use

Var Arr \u003d, "ABC", 1, "1", 1]; RemoveFromArr (Arr, 1); // ["2", "ABC", "1"] var arr \u003d [, 2, "a" ,,]; RemoveFromArr (Arr,); //]

Let Arr \u003d; Console.log (ARR); // Result Let Index \u003d Arr.Indexof (30); if (index\u003e -1) (arr.splice (index, 1);) Console.log (ARR); // Result

Var index \u003d Array.Indexof ("Item"); if (index! \u003d - 1) (array.splice (index, 1);)