admin管理员组文章数量:1405392
How to join .map and .filter to filter and remove duplicate in object array?
I currently have to use two variables for this:
Image example
See code Sandbox example
const arrayOne = [
{
id: 1,
name: "João",
city: {
id: 1,
name: "Rio de Janeiro"
}
},
{
id: 1,
name: "Pedro",
city: {
id: 2,
name: "Salvador"
}
},
{
id: 1,
name: "Tiago",
city: {
id: 1,
name: "Rio de Janeiro"
}
}
];
const arrayTwo = arrayOne.map(function (item, index) {
return item.city;
});
const arrayThree = arrayTwo.filter(
(elem, index, arr) => index === arr.findIndex((t) => t.id === elem.id)
);
How to join .map and .filter to filter and remove duplicate in object array?
I currently have to use two variables for this:
Image example
See code Sandbox example
const arrayOne = [
{
id: 1,
name: "João",
city: {
id: 1,
name: "Rio de Janeiro"
}
},
{
id: 1,
name: "Pedro",
city: {
id: 2,
name: "Salvador"
}
},
{
id: 1,
name: "Tiago",
city: {
id: 1,
name: "Rio de Janeiro"
}
}
];
const arrayTwo = arrayOne.map(function (item, index) {
return item.city;
});
const arrayThree = arrayTwo.filter(
(elem, index, arr) => index === arr.findIndex((t) => t.id === elem.id)
);
Share
Improve this question
asked Nov 4, 2021 at 22:08
Cleiton FreitasCleiton Freitas
53711 silver badges25 bronze badges
2 Answers
Reset to default 5If your filter is just to remove duplicates consider creating a Map which simply overwrites all duplicate city.id
s. This can then be converted back to an array, here using spread syntax on the Map.values()
.
const arrayOne = [
{ id: 1, name: 'João', city: { id: 1, name: 'Rio de Janeiro' } },
{ id: 1, name: 'Pedro', city: { id: 2, name: 'Salvador' } },
{ id: 1, name: 'Tiago', city: { id: 1, name: 'Rio de Janeiro' } },
];
const arrayTwo = [...new Map(arrayOne.map(({ city }) => [city.id, city])).values()];
console.log(arrayTwo);
Just chain them together?
const result = arrayOne.map(function (item, index) {
return item.city;
}).filter(
(elem, index, arr) => index === arr.findIndex((t) => t.id === elem.id)
);
If you mean that you want to map and filter at the same time, then you can use either flatMap
or reduce
as described in another Q/A: https://stackoverflow./a/34398349/211627
本文标签: javascriptHow to join map and filter to filter and remove duplicate in object arrayStack Overflow
版权声明:本文标题:javascript - How to join .map and .filter to filter and remove duplicate in object array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744285883a2598875.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论