Jenan
Jenan

Reputation: 3320

How to delete data from the js array from this data structure?

I need time to compare online and offline time. If is more off-line time than online time - this time I need to delete. When the user has no time line - I need to delete this user.

I have this problem: When going through times and smažuj is: there remains a value of "undefined" - [undefined, undefined] and then this condition can not be satisfied -

if (user.connectionTimes.length === 0) {
        delete users[id];
    }

How do I solve this problem?

I use the following code:

     var users = [];

        users[0] = {
            userId: 1,
            connectionTimes:
                [
                    {onlineTime:30, offlineTime:70},
                    {onlineTime:50, offlineTime:75}
                ]
        };

        users[1] = {
            userId: 2,
            connectionTimes:
                [
                    {onlineTime:80, offlineTime:70}
                ]
        };

        users[2] = {
            userId: 3,
            connectionTimes: []
        };

        for( var i=0; i<users.length; i++) {
        for( var j=0; j<users[i].connectionTimes.length; j++) {
            if( users[i].connectionTimes[j].onlineTime < users[i].connectionTimes[j].offlineTime) {
     delete users[i].connectionTimes[j];           
    //EDIT - this work - users[i].connectionTimes.splice(j, 1);
    //j--;
            }
        }
        if( users[i].connectionTimes.length == 0) {
delete users[i];

            //EDIT - this work - users.splice(i, 1);
            //i--;
        }
    }

        console.log(users);

Upvotes: 1

Views: 1830

Answers (3)

Adam Rackis
Adam Rackis

Reputation: 83358

delete will remove properties from an object, but in an array it simply sets the value in that index to undefined.

var arr = [1, 2, 3];
delete arr[0];
//undefined, 2, 3

To remove an array entry, you can use splice. So instead of:

delete users[id];

You'd do:

users.splice(id, 1);

Upvotes: 2

delete will not remove the index, will only turn the value undefined.
what you are looking for is splice(), try this:

if (user.connectionTimes.length === 0) {
   users[id].splice(id, 1);
}

Upvotes: 1

SLaks
SLaks

Reputation: 887285

delete will leave a hole in the array.

To actually remove the entire slot, call array.splice(index, 1).
This will shift all subsequent slots down by 1 to fill in the hole.

You should do this in a backwards loop, or you'll end up skipping the next item.

Upvotes: 4

Related Questions