gpt4 book ai didi

javascript - 通过 2 个匹配属性从对象数组中删除重复项

转载 作者:行者123 更新时间:2023-11-28 12:52:32 25 4
gpt4 key购买 nike

当键值“hour_from”和“hour_to”相同时,我尝试从字典中删除重复元素。我正在使用 double for (我不记得其他成本较低的算法来做到这一点),但我在索引值方面遇到了问题。

var hours_array = [
{day: "Mon", hour_from: "00:00", hour_to: "00:00"},
{day: "Mon", hour_from: "00:00", hour_to: "00:16"},
{day: "Mon", hour_from: "00:00", hour_to: "00:16"},
{day: "Thu", hour_from: "00:00", hour_to: "00:25"},
{day: "Mon", hour_from: "00:00", hour_to: "00:33"},
{day: "Fri", hour_from: "00:00", hour_to: "00:83"},
{day: "Sat", hour_from: "02:00", hour_to: "05:33"},
{day: "Thu", hour_from: "02:00", hour_to: "05:33"},
{day: "Wed", hour_from: "12:00", hour_to: "14:00"},
{day: "Sun", hour_from: "22:25", hour_to: "13:45"}]

for (let i=0; i< hours_array.length; i++){
for (let j=0; j<=hours_array.length; j++){
if ((hours_array[i]['hour_from'] == hours_array[j]['hour_from']) && (hours_array[i]['hour_to'] == hours_array[j]['hour_to'])){
delete hours_array[j];
}
}
}

我认为这是索引值的错误:

enter image description here

编辑:所需结果:

var hours_array = [
{day: "Mon", hour_from: "00:00", hour_to: "00:00"},
{day: "Mon", hour_from: "00:00", hour_to: "00:16"},
{day: "Thu", hour_from: "00:00", hour_to: "00:25"},
{day: "Mon", hour_from: "00:00", hour_to: "00:33"},
{day: "Fri", hour_from: "00:00", hour_to: "00:83"},
{day: "Sat", hour_from: "02:00", hour_to: "05:33"},
{day: "Wed", hour_from: "12:00", hour_to: "14:00"},
{day: "Sun", hour_from: "22:25", hour_to: "13:45"}]

有什么建议吗?还有更高效的算法吗?感谢您的阅读!

最佳答案

您可以在 Set 的帮助下过滤数组.

如果哈希值(根据 hour_fromhour_to 构建)位于集合中,则该项目将被过滤掉。如果不是,则将哈希值添加到集合中并使用该项目。

var getKey = ({ hour_from, hour_to }) => [hour_from, hour_to].join('|'),
hours_array = [{ day: "Mon", hour_from: "00:00", hour_to: "00:00" }, { day: "Mon", hour_from: "00:00", hour_to: "00:16" }, { day: "Mon", hour_from: "00:00", hour_to: "00:16" }, { day: "Thu", hour_from: "00:00", hour_to: "00:25" }, { day: "Mon", hour_from: "00:00", hour_to: "00:33" }, { day: "Fri", hour_from: "00:00", hour_to: "00:83" }, { day: "Sat", hour_from: "02:00", hour_to: "05:33" }, { day: "Thu", hour_from: "02:00", hour_to: "05:33" }, { day: "Wed", hour_from: "12:00", hour_to: "14:00" }, { day: "Sun", hour_from: "22:25", hour_to: "13:45" }],
unique = hours_array.filter((s => o => !s.has(getKey(o)) && s.add(getKey(o)))(new Set));

console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 通过 2 个匹配属性从对象数组中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59881410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com