Una matriz contiene elementos con identificación duplicada
<div data-id='48444884'>MM</div> <div data-id='11101100'>LL</div> <div data-id='72277727'>TT</div> <div data-id='72277727'>TT</div> <div data-id='48444884'>MM</div> <div data-id='11101100'>LL</div> <div data-id='72277727'>TT</div>¿Puede alguien decirme la mejor manera de ocultar el div de duplicados?
Traté de hacerlo:
Sé cómo crear una matriz con ID únicos a través de un nuevo método Set().map:
const uniqId = new Set([...document.querySelectorAll('[data-id]')].map(id => id.dataset.id));o por arr.filter:
let ids = Array.from(document.querySelectorAll('[data-id]'), id => id.dataset.id); let uniqeid = ids.filter((element, index) => { return ids.indexOf(element) === index; }); console.log('UNIQE ID:', uniqeid);Pero realmente no entiendo cómo cambiar el estilo o agregar clase a cada elemento en la matriz a través de la identificación
Alguien me puede explicar la forma correcta de hacer esto
Al principio, seleccione el primer elemento que tenga la identificación de data-id de uniqeid y luego cambie el style
let ids = Array.from(document.querySelectorAll('[data-id]'), id => id.dataset.id); let uniqeid = ids.filter((element, index) => { return ids.indexOf(element) === index; }); console.log('UNIQE ID:', uniqeid); uniqeid.forEach(id=> { document.querySelector(`[data-id="${id}"]`).style.display = "block"; }); <div data-id='48444884' style="display: none;">MM</div> <div data-id='11101100' style="display: none;">LL</div> <div data-id='72277727' style="display: none;">TT</div> <div data-id='72277727' style="display: none;">TT</div> <div data-id='48444884' style="display: none;">MM</div> <div data-id='11101100' style="display: none;">LL</div> <div data-id='72277727' style="display: none;">TT</div>Otra forma sería usar una matriz que almacene todos los ID usados mientras se itera a través de todos los elementos.
Si la identificación del elemento actual aún no se usó, empujaría esta identificación a la matriz y simplemente continuaría. Si ya se encontró la identificación, simplemente oculte el elemento con display: none
// Here we will store all already used ids, so we know, if any other element, with the same id should be hidden const usedId = []; // We just iterate through all elements with a data attribute of id document.querySelectorAll('[data-id]').forEach(element => { // We check if its own id is already used, if so, we hide this element. // Else we just add the id to the array, so any other element with the same id will be hidden. if(usedId.indexOf(element.dataset.id) === -1){ usedId.push(element.dataset.id); }else{ element.style.display = "none"; } }) <div data-id='48444884'>MM</div> <div data-id='11101100'>LL</div> <div data-id='72277727'>TT</div> <div data-id='72277727'>TT</div> <div data-id='48444884'>MM</div> <div data-id='11101100'>LL</div> <div data-id='72277727'>TT</div>