2016-05-27 24 views
0

簡要背景:我通過每個api檢索來自Google書籍 worldcat的書籍信息。我通過數據解析來創建一個html的div輸出和一個webapp的感興趣的東西。isbn de-duplicate with javascript/jquery

問題:isbns。從每個獲得isbns後,我將它們合併爲一個div。例如:

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

我想消除重複ISBN(例如9781137012920)與JavaScript或jquery的。我可以獲得跨度文本,但是我嘗試過的每個解決方案都失敗了。

任何幫助 - 特別是,與codepen或小提琴 - 這個業餘愛好者將不勝感激。

PS:我知道這個問題的變種已在StackOverflow上解決 - 並相信我,我厭倦了重複! - 但是在幾天的嘗試之後,我還沒有設法解決這個問題。將內容輸入爲var work的示例,但是如何從div中獲取並使其工作?

回答

0

不要使用text()方法是這樣的有回調

$('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>

更多關於尋找獨特的數組元素是指:Remove Duplicates from JavaScript Array

+0

非常感謝你。我會盡量不要想太多的事實,它花了我兩天沒有得到這個權利... – Farhang

0

我想你想是這樣的:

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>

+0

謝謝!你一步一步對我很有幫助。一個感謝的世界 – Farhang

+0

很高興知道它幫助:) –