D
D
Dmitry Sergeevich2015-11-17 20:19:30
JavaScript
Dmitry Sergeevich, 2015-11-17 20:19:30

How to remove duplicate paragraphs with jQuery?

Hey everyone, I urgently need some help from jQuery wizards:

I have a script that iterates over a list, calculates the first letter in an element of the list, and appends it to that element.

$.each(listitems, function (idx, item) {
    item = $(item);
    var firstLetter = $(item).find('a').text().charAt(0);
    $(item).append("<p>"+firstLetter+"</p>").addClass(firstLetter);
  });


Please help me write an exception for the script so that it does not add an already existing letter ..
In short, now 3 M is displayed, and I only need 1.
fiddle.jshell.net/okkm5bnc

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Immortal_pony, 2015-11-17
@CheckOneTwo

var listitems =  $(".works__item")
var usedLetters = []; // Инициализируем массив для учета использованных букв

$.each(listitems, function (idx, item) {
    item = $(item);
    var firstLetter = $(item).find('a').text().charAt(0);
    
    if (usedLetters.indexOf(firstLetter) === -1) { // Продолжаем работать с буквой только в случае, если она еще не использовалась
    	$(item).append("<p>"+firstLetter+"</p>").addClass(firstLetter);
        usedLetters.push(firstLetter); // После обработки помещаем букву в массив использованных букв
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question