Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda