1. 程式人生 > >js Object 陣列去重

js Object 陣列去重

目標:實現成員為 Object 的陣列的去重。

注意,這裡的陣列成員為 Object,而不是數值或者字串。

呼叫方法:

arr = distinct_arr_element(arr);

函式:

/*
 * 在陣列中去除重複項()
 */
var distinct_arr_element = function( arr ){

    if( !arr ) return null ;

    var resultArr = [];

    $(arr).each( function( index, el ){
        var notExist = true ;
        $(resultArr).each( function
(i,element){
if( isObjectValueEqual( el, element ) ){ notExist = false ; return false ; } }); if( notExist ) resultArr.push( el ); }); return resultArr ; } /* * 判斷兩個 Object 的值是否相等 */ function isObjectValueEqual
(a, b) {
// Of course, we can do it use for in Create arrays of property names var aProps = Object.getOwnPropertyNames(a); var bProps = Object.getOwnPropertyNames(b); // If number of properties is different, objects are not equivalent if (aProps.length != bProps.length) { return
false; } for ( var i = 0; i < aProps.length; i++ ) { var propName = aProps[i]; // If values of same property are not equal, objects are not equivalent if (a[propName] !== b[propName]) { return false; } } // If we made it this far, objects are considered equivalent return true; }