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!

2 Answers2

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.

31piy
  • 23,323
  • 6
  • 47
  • 67
  • 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 – Toko Goshadze Apr 06 '18 at 08:30
  • @TokoGoshadze -- don't get confused. Read the difference [here](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons) and then make the decisions. – 31piy Apr 06 '18 at 11:09
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]);
    }
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112