Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
Find index of array elements on div mouseenter. Which is the best of these 3 methods?

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!