Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove object from a JavaScript Array? [duplicate]

Possible Duplicate:
Remove specific element from a javascript array?

Specifically I have an array as follows:

var arr = [     {url: 'link 1'},     {url: 'link 2'},     {url: 'link 3'} ]; 

Now you want to remove valuable element url "link 2" and after removing the only arrays as follows:

arr = [     {url: 'link 1'},     {url: 'link 3'} ]; 

So who can help me this problem? Thanks a lot

like image 311
Messi Avatar asked Jun 14 '12 03:06

Messi


People also ask

How do you remove duplicate objects from an array?

To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.

How do you remove duplicate array elements in JavaScript?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.

How do you find duplicate objects in an array?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do you duplicate an array in JavaScript?

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable.


1 Answers

You could do a filter.

var arr = [   {url: "link 1"},   {url: "link 2"},   {url: "link 3"} ];  arr = arr.filter(function(el){   return el.url !== "link 2"; }); 

PS: Array.filter method is mplemented in JavaScript 1.6, supported by most modern browsers, If for supporting the old browser, you could write your own one.

like image 155
xdazz Avatar answered Oct 11 '22 16:10

xdazz