javascript - 如何删除数组中重复出现的内容?

标签 javascript jquery

我有任何看起来像这样的数组:

[
    { "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/

相关文章:

javascript - 如何让 ExtJS 网格响应式

Javascript:无法更改 div 单击的背景或更改元素的 marginLeft

javascript - Twitter bootstrap 通过 Javascript in rails 管理多个单选按钮

javascript - 多列网格中,如何限制每列的元素数

javascript - 如何在 Bootstrap 中对背景图像应用模糊效果

javascript - 在 jQuery 表绑定(bind)中获取更多数据时,如何在表主体中保留旧数据?

javascript - 如何在客户端合并两个音频文件。 (甚至服务器端)

javascript - 删除 URL 开头和结尾的斜杠

jquery - 我如何在 jQuery 中使用两种不同的方法?

javascript - Angular bootstrap-ui datepicker动态改变minMode