44

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

4
  • 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...
    – user166390
    Commented Jun 14, 2012 at 3:56
  • I have seen this question many times already. Commented Jun 14, 2012 at 4:41
  • 1
    arr.filter(function(element){ return(element.url === 'link 2'? false :true); })
    – Manoj
    Commented Mar 21, 2017 at 11:39
  • var arr = [ {url: "link 1"}, {url: "link 2"}, {url: "link 3"} ]; arr = arr.filter(function(el){ return el.url !== "link 2"; }); Commented Aug 3, 2021 at 17:01

2 Answers 2

36

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.

2
  • 3
    Please include the requirements... not everyone is so lucky to have such function (without a shim).
    – user166390
    Commented Jun 14, 2012 at 3:58
  • Perfect, helped me allot! Commented Jul 27, 2017 at 0:49
4

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;
        }
    }
}
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.