Tengo una serie de elementos con sus identificadores, estampados dentro de mi archivo html; Necesito encontrar el índice en mouseover basado en la misma identificación.
Probé y encontré 3 buenos códigos/soluciones como esta:
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')); })Estas son mis 3 soluciones:
para cada
function findIndex (boxId){ var boxIndex; myArray.forEach(function(el, index){ if (boxId === el._id) { boxIndex = index + 1 } }) return boxIndex; }Mapa + índice de
function findIndex (boxId){ var index = myArray.map(function(el) {return el._id; }).indexOf(boxId); return index; }Mapa + filtro
function findIndex (boxId){ var index = myArray.map((el, i) => el._id === boxId ? i : '').filter(String); return index; }¿Cuál es el mejor para ti? En términos de rendimiento o buen código. Me gusta el primero y el segundo.