I have an array that looks like:
const array = [
{ id: "LAX" },
{ id: "BAS" },
{ id: "TES" },
{ id: "LAX" },
{ id: "LAX" },
{ id: "ATL" },
{ id: "BNA" },
{ id: "LAX" },
];
Here I'm trying to remove duplicate values of id
using Set
[...new Set(array)]
is not currently helping.
I'm basically trying to achieve a result like below:
`["LAX", "BAS", "TES"....]` // with no duplicates.
Any es6 reasons for this?
CodePudding user response:
before using Set to create your data, you should map your data based on a key. this will solve your problem:
const array =[
{id: "LAX"},
{id: "BAS"},
{id: "TES"},
{id: "LAX"},
{id: "LAX"},
{id: "ATL"},
{id: "BNA"},
{id: "LAX"}]
const result = [...new Set(array.map(item => item.id))]
CodePudding user response:
I think this snippet of code will solve your problem.
const array = [
{ id: "LAX" },
{ id: "BAS" },
{ id: "TES" },
{ id: "LAX" },
{ id: "LAX" },
{ id: "ATL" },
{ id: "BNA" },
{ id: "LAX" },
];
const myset = new Set();
array.forEach((value) => myset.add(value.id));
const newArr = Array.from(myset);
CodePudding user response:
let array = [{
id: "LAX"
},
{
id: "BAS"
},
{
id: "TES"
},
{
id: "LAX"
},
{
id: "LAX"
},
{
id: "ATL"
},
{
id: "BNA"
},
{
id: "LAX"
}
];
const unique = [...new Map(array.map((m) => [m.id, m])).values()];
console.log(unique)