我有任何看起来像这样的数组:
[
{ "tempValue": "Sunday CLOSE to CLOSE" },
{ "tempValue": "Sunday CLOSE to 08:30" },
{ "tempValue": "Sunday CLOSE to 08:30" },
{ "tempValue": "Tuesday CLOSE to 08:30" },
{ "tempValue": "Thursday CLOSE to 08:30" }
]
我需要从该数组中删除所有重复项。在上面的示例中,重复项是Sunday
...
所以我尝试了这样的事情:
function unique(list) {
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
unique(hours);
变量hours
是我的数组。
但是我上面的代码不起作用!
有人可以就这个问题提出建议吗?
编辑:
所需的输出是这样的:
[
{ "tempValue": "Tuesday CLOSE to 08:30" },
{ "tempValue": "Thursday CLOSE to 08:30" }
]
最佳答案
我首先计算每天出现的次数,然后创建一个仅包含出现多次的日期的数组。然后,您可以通过数组项中的日期是否包含在该数组中来.filter
:
const input = [{
"tempValue": "Sunday CLOSE to CLOSE"
}, {
"tempValue": "Sunday CLOSE to 08:30"
}, {
"tempValue": "Sunday CLOSE to 08:30"
}, {
"tempValue": "Tuesday CLOSE to 08:30"
}, {
"tempValue": "Thursday CLOSE to 08:30"
}];
const dayCountObj = input.reduce((a, { tempValue }) => {
const day = tempValue.match(/^\S+/)[0];
a[day] = (a[day] || 0) + 1;
return a;
}, {});
const daysToRemove = Object.entries(dayCountObj)
.filter(([, count]) => count > 1)
.map(([day]) => day);
const output = input.filter(({ tempValue }) => {
const day = tempValue.match(/^\S+/)[0];
return !daysToRemove.includes(day);
});
console.log(output);
如果您想将计算复杂度降低到 O(N)
而不是 O(N^2)
,请使用 Set 而不是数组作为 删除天数
:
const input = [{
"tempValue": "Sunday CLOSE to CLOSE"
}, {
"tempValue": "Sunday CLOSE to 08:30"
}, {
"tempValue": "Sunday CLOSE to 08:30"
}, {
"tempValue": "Tuesday CLOSE to 08:30"
}, {
"tempValue": "Thursday CLOSE to 08:30"
}];
const dayCountObj = input.reduce((a, { tempValue }) => {
const day = tempValue.match(/^\S+/)[0];
a[day] = (a[day] || 0) + 1;
return a;
}, {});
const daysToRemove = new Set(
Object.entries(dayCountObj)
.filter(([, count]) => count > 1)
.map(([day]) => day)
);
const output = input.filter(({ tempValue }) => {
const day = tempValue.match(/^\S+/)[0];
return !daysToRemove.has(day);
});
console.log(output);
关于javascript - 如何删除数组中重复出现的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56986301/