-1

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?

pilchard
  • 12,414
  • 5
  • 11
  • 23
user1234
  • 3,000
  • 4
  • 50
  • 102
  • 2
    you're looking for `new Set(array.map(x => x.id))` – gog Dec 17 '22 at 09:04
  • Does this answer your question? [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) – pilchard Dec 17 '22 at 11:38
  • and [Remove duplicate values from JS array](https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array) – pilchard Dec 17 '22 at 11:39

3 Answers3

2

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))]
1

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);

0

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)