使用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' }
]