0

Brief background: I retrieve book info from google books and worldcat via each api. I parse through the data to create an html div outputs with stuff of interest for a webapp.

The problem: the isbns. After getting isbns from each, I merge them into one div. For example:

<span id='tada'>9781137012920 9780230339118 9781137012920 1137012927</span>

I would like to eliminate the duplicate isbn (e.g., 9781137012920) with either javascript or jquery. I can get the text of the span but every solution I have tried has failed thus far.

Any help - esp, with a codepen or fiddle - for this amateur would be greatly appreciated.

PS:I know variations of this question have been addressed on StackOverflow - and believe me that I am sick of duplicates! - but I have not managed to fix this after a couple of days of trying. Examples that type in the content as var work but how do I get it from the div and make it work?

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
farhang
  • 407
  • 1
  • 5
  • 13

3 Answers3

0

I suggest removing the duplicates before making them into the div. If you are getting the values in an array you can eliminate the duplicates easily. Remove Duplicates from JavaScript Array

Community
  • 1
  • 1
MACMAN
  • 1,883
  • 1
  • 21
  • 35
0

Do something like this using text() method with callback

$('span').text(function(i, v) { // use callback to get old value
  return v.split(' ') // split the old value
    .filter(function(v1, i, arr) { // v1 is array element, i is index, arr is iterating array
      return arr.indexOf(v1) == i; // filter unique value by checking the index
    }).join(' ') // join and return the unique values
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='tada'>9781137012920 9780230339118 9781137012920 1137012927</span>

For more about finding unique array element refer : Remove Duplicates from JavaScript Array

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • Thank you ever so much. I will try not to think too much about the fact that it took me two days of not getting this right ... – farhang May 27 '16 at 03:18
0

I think you want something like this :

var string = $('span').text();

var uniqueList=string.split(' ').filter(function(allItems,i,a){
    return i==a.indexOf(allItems);
}).join(' ');

$('#output').append(uniqueList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div>
    <h1>Input</h1>
  <span>9781137012920 9780230339118 9781137012920 1137012927</span>
</div>
<div id="output">
    <h1>Becomes</h1>
</div>
Ani Menon
  • 27,209
  • 16
  • 105
  • 126