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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With