7
    var arr = [
                     {id:2,date:'2010-10-03',des:'goodday'},
                     {id:3,date:'2011-02-13',des:'badday'},
                     {id:4,date:'2011-04-03',des:'niceday'}
                   ];

Now I want to delete {id:3,date:'2011-02-13',des:'badday'} , and then the arr should be

        var arr = [
                     {id:2,date:'2010-10-03',des:'goodday'},
                     {id:4,date:'2011-04-03',des:'niceday'}
                   ];

How should I do?

3 Answers 3

15

Assume the id fields in you Objects are unique you can do the following to delete it. The function to use is Splice:

    var arr = [
        {
        id: 2,
        date: '2010-10-03',
        des: 'goodday'},
    {
        id: 3,
        date: '2011-02-13',
        des: 'badday'},
    {
        id: 4,
        date: '2011-04-03',
        des: 'niceday'}
    ];

    for(var i=0; i<arr.length; i++){
        if(arr[i].id == 3){
            arr.splice(i, 1);  //removes 1 element at position i 
            break;
        }
    }

console.log(arr);  
//should give you 
//                      var arr = [
//                               {id:2,date:'2010-10-03',des:'goodday'},
//                               {id:4,date:'2011-04-03',des:'niceday'}
//                          ];
Sign up to request clarification or add additional context in comments.

Comments

1

See here:

http://wolfram.kriesing.de/blog/index.php/2008/javascript-remove-element-from-array

2 Comments

That's impossible, as the answer you've marked as the solution uses the splice method.
Splice is right, but indexOf can't work in my case. It's not the complete answer
0

arr.splice(1,1); will remove the object at arr[1], and arr[2] will slide into its place.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.