簡體   English   中英

計算對象數組中的重復項

[英]Count duplicates within an Array of Objects

我的服務器端 JS 中有一個對象數組,如下所示:

[
    {
        "Company": "IBM"
    },
    {
        "Person": "ACORD LOMA"
    },
    {
        "Company": "IBM"
    },
    {
        "Company": "MSFT"
    },
    {
        "Place": "New York"
    }
]

我需要遍歷這個結構,檢測任何重復項,然后在每個值旁邊創建一個重復項的計數。

這兩個值必須匹配才能成為重復項,例如“公司”:“IBM”與“公司”:“MSFT”不匹配。

如果需要,我可以選擇更改入站對象數組。 我希望輸出是一個對象,但我真的很難讓它工作。

編輯:這是我到目前為止的代碼,其中 processArray 是上面列出的數組。

var returnObj = {};

    for(var x=0; x < processArray.length; x++){

        //Check if we already have the array item as a key in the return obj
        returnObj[processArray[x]] = returnObj[processArray[x]] || processArray[x].toString();

        // Setup the count field
        returnObj[processArray[x]].count = returnObj[processArray[x]].count || 1;

        // Increment the count
        returnObj[processArray[x]].count = returnObj[processArray[x]].count + 1;

    }
    console.log('====================' + JSON.stringify(returnObj));

例如:

counter = {}

yourArray.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter[key] = (counter[key] || 0) + 1
})

文檔: Array.forEachJSON.stringify

Object.prototype.equals = function(o){
    for(var key in o)
        if(o.hasOwnProperty(key) && this.hasOwnProperty(key))
            if(this[key] != o[key])
                return false;
    return true;
}
var array = [/*initial array*/],
    newArray = [],
    ok = true;
for(var i=0,l=array.length-1;i<l;i++)
    for(var j=i;j<l+1;j++)
    {
       if(!array[i].equals(array[j]))
           newArray.push(array[i]);
    }

使用 ES6,可以將Array#reduce與對象一起使用來存儲計數。

let counts = arr.reduce((acc, curr)=>{
   const str = JSON.stringify(curr);
   acc[str] = (acc[str] || 0) + 1;
   return acc;
}, {});

演示

要創建一個沒有重復的新數組,可以將SetArray#filter一起使用。

let set = new Set;
let res = arr.filter(x => {
  const str = JSON.stringify(x);
  return !set.has(str) && set.add(str);
});

演示

我們需要編寫一個 JavaScript 函數來接收一個這樣的對象數組。 該函數創建並返回一個新數組,其中沒有重復的對象(重復是指具有相同“Country”屬性值的對象。)

此外,該函數應該為每個對象分配一個計數屬性,表示它們在原始數組中出現的次數。

const arr = [
   {
      "Country": "BR",
      "New Lv1−Lv2": "#N/A"
   },
   {
      "Country": "BR",
      "New Lv1−Lv2": "#N/A"
   },
   {
      "Country": "",
      "New Lv1−Lv2": "test"
   }];
   const convert = (arr) => {
      const res = {};
      arr.forEach((obj) => {
         const key = `${obj.Country}${obj["New Lv1−Lv2"]}`;
         if (!res[key]) {
            res[key] = { ...obj, count: 0 };
         };
         res[key].count += 1;
      });
   return Object.values(res);
};
console.log(convert(arr));

了解更多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM