[javascript]將array做distinct,將物件obj的array做distinct

  • 1220
  • 0
  • 2021-12-02

[javascript]將array做distinct,將物件obj的array做distinct

參考自網路,這是目前現階段找到最簡單好懂,且對於不同瀏覽器的相容性相當高的:(連IE 8+都沒問題)

var arr = ['foo', 'bar', 'bar'];

$.each(arr, function(i, value){
    $('div').eq(0).append(value + ' ');
});

$.each(unique(arr), function(i, value){
    $('div').eq(1).append(value  + ' ');
});

function unique(array){
    return $.grep(array,function(el,index){
        return index == $.inArray(el,array);
    });
}

 


執行結果:




如果要將物件obj的array做distinct做distinct,範例如下:

var data = [
{name:"Joe", date:'2018-07-01', amt:250 },
{name:"Mars", date:'2018-07-01', amt:250 },
{name:"Joe", date:'2018-07-02', amt:250 },
{name:"Saturn", date:'2018-07-01', amt:250 },
{name:"Joe", date:'2018-07-02', amt:250 },
{name:"Jupiter", date:'2018-07-01', amt:250 },
];

data = uniqueObjArr(data);
console.log(data);

function uniqueObjArr(arr) {        
    var unique = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
    return unique;
}


執行結果:




參考資料:
jQuery.unique on an array of strings - Stack Overflow
How to get unique values from Object Array Javascript - Stack Overflow