1

I've currently got a implementation which loops through an array within a json document (returned from mongoose) and looks for specific items as below

So what's happening is i'm passing an id in the request header to express and what i need to happen is for it to grab the associated story.users.id.name from the story.users array is returned and then once it has the name send do something with all the other items in the array.

I did try to do this like below:

            for (var i = 0; i < story.users.length; i++) {
                if (story.users[i].id._id == req.headers.id) {
                   var name = story.users[i].id.name
                } else {
                    push.apns(story.users[i].id._id, name + " started a new story");
                }
            } 

Where it would loop through grab the name and then do something with all the other users in the array, however sometimes the else argument fires first so the name variable is undefined.

So i resorted to running two if loops after each other like below:

            for (var i = 0; i < story.users.length; i++) {
                if (story.users[i].id._id == req.headers.id) {
                    var name = story.users[i].id.name
                }
            };
            for (var i = 0; i < story.users.length; i++) {
                if (story.users[i].id._id == req.headers.id) {
                } else {
                    push.apns(story.users[i].id._id, name + " started a new story");
                }
            }

But there must be a better way to the above rather than looping through an array twice?

0

1 Answer 1

2

What you do looks like the right solution (with the goal you seem to have). There's no real simple way to do only one loop.

You could make it faster and cleaner, though :

var name; // this is just cleaner than to define it in the loop
for (var i = 0; i < story.users.length; i++) {
    if (story.users[i].id._id == req.headers.id) {
        name = story.users[i].id.name;
        break; // don't loop over the other elements
    }
};
for (var i = 0; i < story.users.length; i++) {
    if (story.users[i].id._id !== req.headers.id) {
        push.apns(story.users[i].id._id, name + " started a new story");
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I've updated my code to go with this cleaner way of doing it

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.