Lukas
Lukas

Reputation: 7734

How to remove duplicated content/value with jQuery

So, i have span element where i appending some content - sometimes this content is duplicated. How to remove this one value which is duplicate of another ...

This is how looks like my output html:

<span class="some_class">
   "value01" 
   "value01" 
   "value02" 
   "value03" 
   "value03" 
</span>

I can't add any function because i have no idea how to do this, can u help me?

Upvotes: 1

Views: 1315

Answers (2)

Wojciech Dłubacz
Wojciech Dłubacz

Reputation: 219

If these values are being added by JS code, then You can make sth like this:

http://jsfiddle.net/Sahadar/Nzs52/5/

You just have to make object which will store all strings placed inside this span, then just before insertion check if this inserted string is already in store object.

function(event) {
        var textareaValue = textarea.value();
        if(insertedTexts[textareaValue]) {
             event.preventDefault();
             textarea.value('');                         
         } else {
             insertedTexts[textareaValue] = true;
             someSpan.append("\""+textareaValue+"\"");
         }
    }

If these values are already inside span, use function as follows:

var someSpan = $('.some_class');
var insertedTexts = [];

var result = someSpan.text().match(/"\w+(?=\")/gm);
result = result.map(function(value) {
    return value.substring(1,value.length);
});
result.forEach(function(value) {
    if(insertedTexts.indexOf(value) === -1) {
        insertedTexts.push(value);
    }
});
var newSpanText = "\""+insertedTexts.join('""')+"\"";
someSpan.text(newSpanText);
console.info(result, insertedTexts);

It's rebuilding span text (trimming etc.) but main functinality is preserved.

jsFiddle working copy:

http://jsfiddle.net/Sahadar/kKNXG/6/

Upvotes: 2

hyankov
hyankov

Reputation: 4120

Create an array variable

var vals = [];

which keeps track of the items. Then, in your function that appends items to the span check:

if (vals.indexOf("Mynewvalue") > -1) {
  // Add to the span...
}

Upvotes: 0

Related Questions