试图对一组对象进行排序但是拼接不是一个函数?

时间:2016-05-09 08:47:42

标签: javascript arrays

全局图片是我试图从对象数组中删除重复项。具有相同adsId和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不是函数。

任何帮助都是有帮助的。

3 个答案:

答案 0 :(得分:1)

您可以将Array#filter与已插入元素的哈希表一起使用。

{
    $match : 
    { 
        "q0":"1"
    }
},

答案 1 :(得分:1)

您无法在 SessionStorage 中存储数组/对象。
Web存储只能存储字符串。
sessionStorage['events']密钥中有一个字符串,通过JSON.stringify()方法处理。
处理数组进一步过滤 - 解码带有JSON.parse()方法的字符串,如:

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

http://plnkr.co/edit/ZcJr9zg9PeUeRX4kRhbW?p=preview

答案 2 :(得分: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>");