Reputation: 63
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!
Upvotes: 0
Views: 103
Reputation: 68635
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]);
}
}
Upvotes: 3
Reputation: 23859
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
.
Upvotes: 3