35

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

cнŝdk
  • 28,676
  • 7
  • 47
  • 67
Messi
  • 351
  • 1
  • 3
  • 3
  • 4
    I do not think this is a a direct duplicate of that question. In the other question only a primitive value is used. `indexOf` will **not** work here. So, unless the index is (always) known, a bit of the puzzle is missing with `splice`... –  Jun 14 '12 at 03:56
  • I have seen this question many times already. – Derek 朕會功夫 Jun 14 '12 at 04:41
  • `arr.filter(function(element){ return(element.url === 'link 2'? false :true); })` – Manoj Mar 21 '17 at 11:39

2 Answers2

31

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.

xdazz
  • 149,740
  • 33
  • 229
  • 258
3

Use the splice function to remove an element in an array:

arr.splice(1, 1);

If you would like to remove an element of the array without knowing the index based on an elements property, you will have to iterate over the array and each property of each element:

for(var a = 0; a < arr.length; a++) {
    for(var b in arr[a]) {
        if(arr[a][b] === 'link 2') {
            arr.splice(a, 1);
            a--;
            break;
        }
    }
}
xcopy
  • 2,108
  • 17
  • 22