Nic Lin's Blog

喜歡在地上打滾的 Rails Developer

Array 去除重複數值或 Object 的方法

ES6 之後可以使用 Set

var uniqArray = new Set([1, 2, 3])

uniqArray
// Set(3) {1, 2, 3}

uniqArray.add(3)
// Set(3) {1, 2, 3}

uniqArray.add(4)
// Set(4) {1, 2, 3, 4}

Javascript: Remove Duplicates From Array Of Objects

如果 Array 裡面是放 Object 就不適用了,網路上查到比較多的答案是有人寫了一個專門去除重複元素的 function

function removeDuplicates(originalArray, prop) {
     var newArray = [];
     var lookupObject  = {};

     for(var i in originalArray) {
        lookupObject[originalArray[i][prop]] = originalArray[i];
     }

     for(i in lookupObject) {
         newArray.push(lookupObject[i]);
     }
      return newArray;
 }

Usage:

removeDuplicates(arrayWithDuplicates, 'size');

Returns:

[
    {
        "color": "red",
        "size": "small"
    },
    {
        "color": "blue",
        "size": "medium"
    },
    {
        "color": "red",
        "size": "large"
    }
]

And:

removeDuplicates(arrayWithDuplicates, 'color');

Returns:

[
    {
        "color": "red",
        "size": "small"
    },
    {
        "color": "green",
        "size": "small"
    },
    {
        "color": "blue",
        "size": "medium"
    }
]

參考來源

comments powered by Disqus