使用JavaScript中的URL值从数组中删除重复项
假设我们有一个像这样的对象数组-
const arr = [
{
url: 'www.example.com/hello',
id: "22"
},
{
url: 'www.example.com/hello',
id: "22"
},
{
url: 'www.example.com/hello-how-are-you',
id: "23"
},
{
url: 'www.example.com/i-like-cats',
id: "24"
},
{
url: 'www.example.com/i-like-pie',
id: "25"
}
];我们需要编写一个JavaScript函数,该函数接受一个这样的对象数组。该函数应从数组中删除具有重复ID键的此类对象。我们必须不使用下划线之类的库来执行此操作。
让我们为该函数编写代码-
示例
为此的代码将是-
const arr = [
{
url: 'www.example.com/hello',
id: "22"
},
{
url: 'www.example.com/hello',
id: "22"
},
{
url: 'www.example.com/hello−how−are−you',
id: "23"
},
{
url: 'www.example.com/i−like−cats',
id: "24"
},
{
url: 'www.example.com/i−like−pie',
id: "25"
}
];
const removeDuplicate = (arr = []) => {
const map = {};
for(let i = 0; i < arr.length; ){
const { id } = arr[i];
if(map.hasOwnProperty(id)){
arr.splice(i, 1);
}else{
map[id] = true;
i++;
};
};
};
removeDuplicate(arr);
console.log(arr);输出结果
控制台中的输出将是-
[
{ url: 'www.example.com/hello', id: '22' },
{ url: 'www.example.com/hello-how-are-you', id: '23' },
{ url: 'www.example.com/i-like-cats', id: '24' },
{ url: 'www.example.com/i-like-pie', id: '25' }
]热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下