使用Javascript查找对象中的重复值

编程入门 行业动态 更新时间:2024-10-18 14:14:05
本文介绍了使用Javascript查找对象中的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在努力解决自己遇到的问题.我有一个包含对象的数组,像这样:

I've been trying to work out a problem I'm having. I have an array with objects in it, like this:

var array = [ { name: "Steven Smith", Country: "England", Age: 35 }, { name: "Hannah Reed", Country: "Scottland", Age: 23 }, { name: "Steven Smith", Country: "England", Age: 35 }, { name: "Robert Landley", Country: "England", Age: 84 }, { name: "Steven Smith", Country: "England", Age: 35 }, { name: "Robert Landley", Country: "England", Age: 84 } ];

我想获取其中具有重复值并基于要搜索的值的对象.即,我想获取具有重复值名称"和年龄"但重复国家/地区"的对象,所以我最终得到:

I want to get the objects that have duplicate values in them and based on what values to search for. I.e , I want to get the object that has a duplicate value "name" and "age" but nog "country" so I will end up with:

[ { name: "Steven Smith", Country: "England", Age: 35 }, { name: "Steven Smith", Country: "England", Age: 35 }, { name: "Robert Landley", Country: "England", Age: 84 }, { name: "Steven Smith", Country: "England", Age: 35 }, { name: "Robert Landley", Country: "England", Age: 84 } ];

如果一直在尝试

array.forEach(function(name, age){ if(array.name == name || array.age == age){ console.log(the result) } })

但这仅检查对象的值是否等于它们自己.

But that only checks if the values of the object is equal to them self.

有人可以帮助我吗?

推荐答案

您可以使用2 reduce.第一个是对数组进行分组.第二个是仅包含具有1个以上元素的组.

You can use 2 reduce. The first one is to group the array. The second one is to include only the group with more than 1 elements.

var array = [{"name":"Steven Smith","Country":"England","Age":35},{"name":"Hannah Reed","Country":"Scottland","Age":23},{"name":"Steven Smith","Country":"England","Age":35},{"name":"Robert Landley","Country":"England","Age":84},{"name":"Steven Smith","Country":"England","Age":35},{"name":"Robert Landley","Country":"England","Age":84}] var result = Object.values(array.reduce((c, v) => { let k = v.name + '-' + v.Age; c[k] = c[k] || []; c[k].push(v); return c; }, {})).reduce((c, v) => v.length > 1 ? c.concat(v) : c, []); console.log(result);

更多推荐

使用Javascript查找对象中的重复值

本文发布于:2023-11-07 06:02:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565727.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:象中   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!