Abo*_*rgh 5 javascript arrays sorting function
我一直在尝试解决我遇到的问题。我有一个带有对象的数组,像这样:
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
}
];
Run Code Online (Sandbox Code Playgroud)
我想获取其中具有重复值并基于要搜索的值的对象。即,我想要获取具有重复值“名称”和“年龄”但重复“国家/地区”的对象,所以我最终得到:
[
{
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
}
];
Run Code Online (Sandbox Code Playgroud)
如果试图做
array.forEach(function(name, age){
if(array.name == name || array.age == age){
console.log(the result)
}
})
Run Code Online (Sandbox Code Playgroud)
但这仅检查对象的值是否等于自身。
有谁能够帮助我?
我参加聚会有点晚了,但这可能会帮助面临同样问题的人,因为我相信这是一个更容易理解的解决方案:
let duplicates = [];
array.forEach((el, i) => {
array.forEach((element, index) => {
if (i === index) return null;
if (element.name === el.name && element.Age === el.Age) {
if (!duplicates.includes(el)) duplicates.push(el);
}
});
});
console.log("duplicates", duplicates);
Run Code Online (Sandbox Code Playgroud)
有两件事可能难以理解:
编辑:一个更好的解决方案是这样的:
const duplicates = array
.map((el, i) => {
return array.find((element, index) => {
if (i !== index && element.name === el.name && element.Age === el.Age) {
return el
}
})
})
.filter(x => x)
console.log("dupliactes:", duplicates)
Run Code Online (Sandbox Code Playgroud)
它没有副作用,所有逻辑都在一个 if 语句中。需要过滤器来整理未定义的实例。
您可以使用2 reduce
。第一个是对数组进行分组。第二个是仅包含具有1个以上元素的组。
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);
Run Code Online (Sandbox Code Playgroud)