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!
-
And what's your code with "array helpers"?user202729– user2027292018年04月06日 08:12:16 +00:00Commented Apr 6, 2018 at 8:12
2 Answers 2
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.
2 Comments
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
Explore related questions
See similar questions with these tags.