I have an array of elements with their ids, stamped inside my html file; I need to find the index on mouseover based on the same id.
I have tried and found 3 good codes/solutions like this:
HTML
<div class="element" data-id="3"> </div>
<div class="element" data-id="2"> </div>
<div class="element" data-id="1"> </div>
<div class="element" data-id="4"> </div>
myArray = [{ _id:1}, {_id:2}, { _id:3}, { _id:4}];
$('.element').on('mouseenter', function (){
findIndex($(this).data('id'));
})
These are my 3 solutions:
forEach
function findIndex (boxId){
var boxIndex;
myArray.forEach(function(el, index){
if (boxId === el._id) {
boxIndex = index + 1
}
})
return boxIndex;
}
Map + indexOf
function findIndex (boxId){
var index = myArray.map(function(el) {return el._id; }).indexOf(boxId);
return index;
}
Map + filter
function findIndex (boxId){
var index = myArray.map((el, i) => el._id === boxId ? i : '').filter(String);
return index;
}
Which is the best for you? In terms of performance or good code. I like the first and the second.