3 回答

TA貢獻1863條經驗 獲得超2個贊
假設您想保留最近一年的條目,您可以保留電子郵件地址和您所見年份的地圖??丛u論:
// The new list
const filtered = [];
// Known emails
const known = new Map();
// Loop through...
for (const entry of obj) {
// Get this email and expiry
const {email, expiryYear} = entry;
// Get the previous info if any
const previous = known.get(email);
if (previous) {
// If the previous one is older than this one,
// replace it with this one
if (previous.expiryYear < expiryYear) {
filtered[previous.index] = entry;
}
} else {
// Add this to the known list and the filtered array
known.set(email, {
index: filtered.length,
expiryYear
});
filtered.push(entry);
}
}
const obj = [
{
"id":"1",
"name":"a",
"email":"[email protected]",
"expiryYear":"2020"
},
{
"id":"2",
"name":"a",
"email":"[email protected]",
"expiryYear":"2019"
},
{
"id":"3",
"name":"b",
"email":"[email protected]",
"expiryYear":"2020"
},
];
// The new list
const filtered = [];
// Known emails
const known = new Map();
// Loop through...
for (const entry of obj) {
// Get this email and expiry
const {email, expiryYear} = entry;
// Get the previous info if any
const previous = known.get(email);
if (previous) {
// If the previous one is older than this one,
// replace it with this one
if (previous.expiryYear < expiryYear) {
filtered[previous.index] = entry;
}
} else {
// Add this to the known list and the filtered array
known.set(email, {
index: filtered.length,
expiryYear
});
filtered.push(entry);
}
}
console.log(filtered);
這樣做的好處是不會不斷地重新掃描新列表以查找已知條目。

TA貢獻1898條經驗 獲得超8個贊
您可以根據您想要的唯一鍵過濾掉整個對象,如下所示。
const obj =
[
{
"id": "1",
"name": "a",
"email": "[email protected]",
"expiryType": "premium"
},
{
"id": "2",
"name": "b",
"email": "[email protected]",
"expiryType": "gold"
},
{
"id": "3",
"name": "b",
"email": "[email protected]",
"expiryType": "premium"
}
]
function arrayUnique(arr, uniqueKey) {
const flagList = []
return arr.filter(function(item) {
if (flagList.findIndex(flagItem => flagItem[uniqueKey] === item[uniqueKey]) === -1) {
flagList.push(item)
return true
}
})
}
方法調用....
let newObj = arrayUnique(obj,'email')
輸出:
newObj = [
{
"id": "1",
"name": "a",
"email": "[email protected]",
"expiryType": "premium"
},
{
"id": "3",
"name": "b",
"email": "[email protected]",
"expiryType": "premium"
}
]

TA貢獻1868條經驗 獲得超4個贊
你可以用 2 個循環簡單地做到這一點。也許不是禁食,而是最簡單的:
function deleteDouble(array, objectKey) {
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array.length; j++) {
if (i == j) {
continue;
}
if (array[i][objectKey] == array[j][objectKey]) {
array.splice(i, 1);
i = 0;
j = 0;
break;
}
}
}
return array;
}
deleteDouble(obj, "email");
添加回答
舉報