我有一个对象数组,我想过滤返回具有重复属性值的对象。
My Array of Objects:
values = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
{ id: 4, name: 'a' }
];
我想在一个新的对象数组中得到的结果:
duplicateValues = [
{ id: 1, name: 'a' },
{ id: 4, name: 'a' }
];
- 使用Array.prototype.reduce将值按
name
进行分组 - 使用Array.prototype.filter. 过滤长度大于
- 最后使用array .prototype.flat. 平整化结果数组
1
的组const values = [{ id: 1, name: "a" }, { id: 2, name: "b" }, { id: 3, name: "c" }, { id: 4, name: "a" }];
const duplicates = Object.values(
values.reduce((r, v) => ((r[v.name] ??= []).push(v), r), {})
)
.filter((g) => g.length > 1)
.flat();
console.log(duplicates);
打印稿解决方案:
type Values = { id: number, name: string }[];
const values = [{ id: 1, name: "a" }, { id: 2, name: "b" }, { id: 3, name: "c" }, { id: 4, name: "a" }];
const duplicates = Object.values(
values.reduce(
(r: { [k: string]: Values }, v) => ((r[v.name] ??= []).push(v), r),
{}
)
)
.filter((g) => g.length > 1)
.flat();
console.log(duplicates);
您可以复制数组并根据值进行过滤。在这里查看演示:https://stackblitz.com/edit/typescript-xww2ai?file=index.ts
const values = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
{ id: 4, name: 'a' },
];
const copyValues = [...values];
const duplicateObjects = values.filter(
(v) => copyValues.filter((cp) => cp.name === v.name).length > 1
);
console.log(duplicateObjects);
function findDuplicates(data) {
// map containing already added names.
const existing = new Map();
// set containing names, which were parsed in passed and added at future occurence of that name
const consideredReadd = new Set();
// final output array
const output = [];
data.forEach((item) => {
if(!existing.has(item.name)) {
// if not present in already parsed names, add in map
existing.set(item.name, item);
} else {
if (!consideredReadd.has(item.name)) {
// if is already present and past record isn't added in output array, add that record in output array and set the key in data set.
consideredReadd.add(item.name);
output.push(existing.get(item.name));
}
// push the current item as it existed in past
output.push(item);
}
});
// return output array
return output;
}
let values = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
{ id: 4, name: 'a' }
];
duplicateValues = findDuplicates(values);
console.log(duplicateValues);