首页 > 编程 > JavaScript > 正文

JS实现的Object数组去重功能示例【数组成员为Object对象】

2019-11-19 12:10:52
字体:
来源:转载
供稿:网友

本文实例讲述了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程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表