从数组中获取重复名称数据
方法一:
<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"}]