这篇文章主要介绍了JS如何实现的Object数组去重功能,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
1、能够嵌入动态文本于HTML页面。2、对浏览器事件做出响应。3、读写HTML元素。4、在数据被提交到服务器之前验证数据。5、检测访客的浏览器信息。6、控制cookies,包括创建和修改等。7、基于Node.js技术进行服务器端编程。
本文实例讲述了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':'jb51.net'},{'name':'jb51.net'},{'age':10},{'age':12}];
console.log(distinct_arr_element(arrDemo))
</script>
使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码,可得如下运行结果:
感谢你能够认真阅读完这篇文章,希望小编分享的“JS如何实现的Object数组去重功能”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。