Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda