0

So today I was learning about some ES6 array helpers, and I wanted to change my existing for loops with them, but I can not get same result as i was taking with for loop

function comment(){
    let index;
    for(let i = 0; i < commentArray.length; i++){
        if(commentArray[i]._id == req.params.commentId){
            index = commentArray.indexOf(commentArray[i]);
        }
    }
    return index;
}
var com = comment();

It is nodejs and I am trying to get element index from database, and than pull from it, my code works just fine, but I want to change it with array helper, I guess I need find helper, but I can not make it work!

1
  • And what's your code with "array helpers"? Commented Apr 6, 2018 at 8:12

2 Answers 2

3

You can replace your for loop with this one-liner which uses Array#findIndex:

let index = commentArray.findIndex(comment => comment._id === req.params.commentId);

When this line executes, it will assign the index of comment, which has _id attribute same as req.params.commentId.

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

2 Comments

works pretty well! just change triple equal sign to double, because with triple it gave me silly error when index equaled -1, i guess that is because comment._id is coming from db as string <3 thanks
@TokoGoshadze -- don't get confused. Read the difference here and then make the decisions.
3

If you want to find the index of the item in the array based on some condition, you can use findIndex function

commentArray.findIndex(comment => comment._id === req.params.commentId)

Also with your current code with for loop, I think you need return the index as soon as it is found and not let the loop iterate till the end.

for(let i = 0; i < commentArray.length; i++){
    if(commentArray[i]._id == req.params.commentId){
        return commentArray.indexOf(commentArray[i]);
    }
}

1 Comment

thanks for answer, it worked, and ill keep in mind to return index when its found next time!

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.