本文實例講述了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;}
完整測試示例如下:
<script src="http://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script><script>/* * 在數組中去除重復項() */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;}var arrDemo=[{'name':'VeVB.COm'},{'name':'VeVB.COm'},{'age':10},{'age':12}];console.log(distinct_arr_element(arrDemo))</script>
使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.VeVB.COm/code/HtmlJsRun測試上述代碼,可得如下運行結果:
PS:這里再為大家提供幾款相關工具供大家參考使用:
在線去除重復項工具:
http://tools.VeVB.COm/code/quchong
在線文本去重復工具:
http://tools.VeVB.COm/aideddesign/txt_quchong
更多關于JavaScript相關內容還可查看本站專題:《JavaScript數組操作技巧總結》、《JavaScript字符與字符串操作技巧總結》、《JavaScript遍歷算法與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript數學運算用法總結》、《JavaScript數據結構與算法技巧總結》及《JavaScript錯誤與調試技巧總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答