1

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);

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How do I use this function "splice" in this condition? if (connectionTime.onlineTime < connectionTime.offlineTime) { delete user.connectionTimes[i]; }
user.connectionTimes.splice(i, 1)?
2

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);

Comments

1

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

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.