我想从数组中删除object的每个副本:
const object = [
{ label: "SUA", value: "sua" },
{ label: "SUA", value: "sua" },
{ label: "Florida", value: "florida" }
];
console.log(object.map(i=> [...new Set(i)]))
最后,我必须这样做:
const object = [
{ label: "Florida", value: "florida" }
];如何在我的代码中做到这一点?
发布于 2020-10-28 14:50:29
您可以使用2 for循环来实现您的功能。
let result = [];
for(let i=0;i<object.length ;i++) {
let isDuplicate = false;
for(let j=0; j<object.length;j++) {
if(object[i].label === object[j].label && object[i].value === object[j].value && i !== j) {
isDuplicate = true;
}
}
if(!isDuplicate) result.push(object[i]);
}发布于 2020-10-28 14:54:12
不管您希望在数组中保留多少个元素的副本,都可以通过定义创建一个映射Map<Location, number>,并将每个Location对象出现的次数列成表格。然后,只取每个元素并将其附加到数组中一次。
type Location = {label: string, value: string};
const object: Location[] = [
{ label: "SUA", value: "sua" },
{ label: "SUA", value: "sua" },
{ label: "Florida", value: "florida" }
];
const objects: Map<Location, number> = new Map();
for (const location of object)
if (objects.has(location))
objects.set(location, objects.get(location) + 1);
else
objects.set(location, 1);
const filtered: Location[] = [];
for (const location of objects)
if (location[1] === 1) // You change 1 to any value depending on how many copies of each you'd like.
filtered.push(location[0];备注为了清晰起见,这是TypeScript,但概念是相同的。
发布于 2020-10-28 14:59:55
快捷方式:
const object = [
{ label: "SUA", value: "sua" },
{ label: "SUA", value: "sua" },
{ label: "Florida", value: "florida" }
];
const a = object.filter((v, i, a) => a.findIndex(t => (t.label ===
v.label && t.value === v.value)) === i);
console.log(a);
https://stackoverflow.com/questions/64567631
复制相似问题