2016-05-09 48 views
0

全局圖是我試圖從對象數組中刪除重複項。具有相同advertId和leadboxId的對象是相當重複的,但出於測試目的,我只檢查advertIds嘗試排序對象數組,但拼接不是一個函數?

我從sessionStorage中獲取此數組並刪除重複項。

var testSort = function() { 
    var events = []; 
    events = sessionStorage.events; 
    console.log("events unsorted"); 
    console.log(events); 
    for (var i = 0; i < events.length; i++) { 
     for (var x = i + 1; x < events.length; x++) { 
      if (events[x].advertId == events[i].advertId) { 
       events.splice(x, 1); 
       --x; 
      } 
     } 
     // add 
    } 

控制檯打印出事件數組作爲這樣的:

[{"module":"slick_module","eventType":"swipe","leadboxId":"1565","advertId":"5653","length":"length of event","time":1462783354789,"posted":"postedStatus"},{"module":"slick_module","eventType":"swipe","leadboxId":"1565","advertId":"56527","length":"length of event","time":1462783357590,"posted":"postedStatus"}] 

這是不是一個很好的陣列? 當試圖拼接這個我得到的錯誤,events.splice不是一個函數。

任何幫助是aprecciated。

+0

呃...你有沒有檢查'events'是否爲空? –

+0

這是我登錄上面的同一個事件,在拼接之前它似乎仍然被填滿。 – JSB

+0

在for循環中拼接時,必須注意所有變換索引。你最好使用'Array.prototype.filter()'。 – Redu

回答

1

不能陣列/對象存儲在的sessionStorage
Web存儲只能存儲字符串。
您在sessionStorage['events']密鑰中有一個字符串,通過JSON.stringify()方法處理。
爲了處理陣列,用於進一步過濾 - 該字符串與JSON.parse()方法等進行解碼:

var arr = JSON.parse(sessionStorage['events']); 
... 

https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API

+0

是的,我忘了這一點。漢克剛剛在你面前指出了這一點。但你的解決方案是唯一的答案,所以我將接受這一點。 – JSB

1

您可以使用Array#filter和已經插入元素的散列表。

var array = [{ "module": "slick_module", "eventType": "swipe", "leadboxId": "1565", "advertId": "5653", "length": "length of event", "time": 1462783354789, "posted": "postedStatus" }, { "module": "slick_module", "eventType": "swipe", "leadboxId": "1565", "advertId": "56527", "length": "length of event", "time": 1462783357590, "posted": "postedStatus" }, { "module": "slick_module", "eventType": "swipe", "leadboxId": "1565", "advertId": "56527", "length": "length of event", "time": 1462783357590, "posted": "postedStatus" }], 
 
    filtered = array.filter(function (a) { 
 
     var key = a.leadboxId + '|' + a.advertId; 
 
     if (!this[key]) { 
 
      this[key] = true; 
 
      return true; 
 
     } 
 
    }, Object.create(null)); 
 

 
document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>');

+0

這將返回相同的錯誤,但是這次使用過濾器?出於某種原因,我的數組不被視爲數組?但控制檯輸出似乎表明它是一個數組 – JSB

0

一如既往Array.prototype.reduce()以幫助與單個襯墊

var events = [{"module":"slick_module","eventType":"swipe","leadboxId":"1565","advertId":"5653","length":"length of event","time":1462783354789,"posted":"postedStatus"},{"module":"slick_module","eventType":"swipe","leadboxId":"1565","advertId":"56527","length":"length of event","time":1462783357590,"posted":"postedStatus"}], 
 
    filtered = events.reduce((p,c) => !~p.findIndex(e => e.advertId == c.advertId) ? p.concat(c) : p, []); 
 
document.write("<pre>" + JSON.stringify(filtered, null,2) + "</pre>");