Javascript查找哪些对象在数组中具有重复的属性

时间:2018-04-22 22:53:33

标签: javascript

我有这个数组:

          "order": [
            {  "item_name": " Corn Pie",
                "item_status": "ready",
                "extras": ["French Fries","Bacon"]
            },
            {  "item_name": " Corn Pie",
                "item_status": "ready",
                "extras": ["French Fries","Bacon"]
            },
            {  "item_name": " Corn Pie",
                "item_status": "ready",
                "extras": ["French Fries","Bacon"]
            },
            {  "item_name": " Corn Pie",
                "item_status": "ready",
                "extras": ["French Fries","Bacon"]
            },
            {  "item_name": " Corn Pie",
                "item_status": "ready",
                "extras": []
            },
            {  "item_name": " Corn Pie",
                "item_status": "ready",
                "extras": ["French Fries"]
            },
            {  "item_name": " Corn Pie",
                "item_status": "waiting",
                "extras": ["French Fries","Bacon"]
            }]

所以我需要找到哪些对象 复制..要复制所有3个属性必须相同..我可以通过这样做来实现:

order = order.filter((item, index, self) =>
        index === self.findIndex((t) => (
            (t.item_name === item.item_name) && (t.item_status === item.item_status) && (t.extras.length === item.extras.length)
        ))
    )

这段代码就像一个魅力......我可以理解它为什么以及它是如何工作的但是我需要知道哪些元素被过滤了多少次以及它做了多少次。

任何想法?提前谢谢..我从这篇帖子post filter

中选了过滤器

来自作者Eydrian,我希望我可以发表评论直接询问,但我没有声誉发表评论..所以我在这里..

更清楚,我需要知道哪些元素在哪里 重复以及过滤了多少次,例如此元素

 {  "item_name": " Corn Pie",
            "item_status": "ready",
            "extras": ["French Fries","Bacon"]
        }

将被过滤4次我需要知道该信息

1 个答案:

答案 0 :(得分:2)

这是一个穴居人解决方案(arr是你的数组,没有"顺序"键):

arr.map(function(d,i){return JSON.stringify(d)})//stringfy the object
.map(function(d,i,a){//we will have multiple arrays with identical content, select the latest one
    return i === a.lastIndexOf(d) && a.filter(function(dd,ii){
        return d === dd
    })
}).filter(function(d){//filter false
    return d;
}).map(function(d,i){//map back to the same object with additional repeated key
    var retValue = JSON.parse(d[0]);
    retValue.repeated = d.length;
    return retValue;    
});

你明白了:

"[
    {
        "item_name": " Corn Pie",
        "item_status": "ready",
        "extras": [
            "French Fries",
            "Bacon"
        ],
        "repeated": 4
    },
    {
        "item_name": " Corn Pie",
        "item_status": "ready",
        "extras": [],
        "repeated": 1
    },
    {
        "item_name": " Corn Pie",
        "item_status": "ready",
        "extras": [
            "French Fries"
        ],
        "repeated": 1
    },
    {
        "item_name": " Corn Pie",
        "item_status": "waiting",
        "extras": [
            "French Fries",
            "Bacon"
        ],
        "repeated": 1
    }
]"