HLJ 发布于
2018-08-24 14:17:27
118阅读

从数组中获取重复名称数据

从数组中获取重复名称数据
方法一:
<script type="text/javascript">
const arr = [
    {Name: 'test',coolProperty: 'yeahCool1'},
    {Name: 'test1',coolProperty: 'yeahCool2'},
    {Name: 'test2',coolProperty: 'yeahCool3'},
    {Name: 'test3',coolProperty: 'yeahCool4'},
    {Name: 'test',coolProperty: 'yeahCool5'}
];
const counts = arr.reduce((a, { Name }) => {
a[Name] = (a[Name] || 0) + 1;
return a;
}, {});
console.log(arr.filter(({ Name }) => counts[Name] === 2));
</script>
方法二:
<script type="text/javascript">
const arr = [
    {Name: 'test',coolProperty: 'yeahCool1'},
    {Name: 'test1',coolProperty: 'yeahCool2'},
    {Name: 'test2',coolProperty: 'yeahCool3'},
    {Name: 'test3',coolProperty: 'yeahCool4'},
    {Name: 'test',coolProperty: 'yeahCool5'}
];
let getCount = (name)=>{
  return arr.filter(o => o.Name == name).length;
}
console.log(arr.reduce((r,item) => {
  let len = getCount(item.Name);
  return r.concat(len>1?item:[]);
}, []));
</script>
输出结果:
[{"Name":"test","coolProperty":"yeahCool1"},{"Name":"test","coolProperty":"yeahCool5"}]

当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2018-08-24/206.html
最后生成于 2024-06-22 12:02:50
此内容有帮助 ?
0