1

I'm trying to build a method in javascript which can filter from an array of object one only value and have a result that value only once without having duplicates

sharing a snippet and more details what I want to achieve

const arr = [{
  "id": "1",
  "value": "something"
}, {
  "id": "1",
  "value": "something"
}, {
  "id": "2",
  "value": "something"
}, {
  "id": "2",
  "value": "something"
},

{
  "id": "3",
  "value": "something"
},
{
  "id": "3",
  "value": "something"
},
{
  "id": "3",
  "value": "something"
}];

const result = arr.filter(res => res.id).map(ele => ele.id);

console.log(result);

As you see result is an array like this

["1", "1", "2", "2", "3", "3", "3"]

What I would like to get is as follow

["1", "2", "3"]

The idea is to extract only one ID per result.

Jakub
  • 2,367
  • 6
  • 31
  • 82

1 Answers1

0

You can use a Set as follows:

const arr = [
  { "id": "1", "value": "something" }, 
  { "id": "1", "value": "something" }, 
  { "id": "2", "value": "something" }, 
  { "id": "2", "value": "something" },
  { "id": "3", "value": "something" },
  { "id": "3", "value": "something" },
  { "id": "3", "value": "something" }
];

const result = [...arr.reduce((set,{id}) => {
  set.add(id);
  return set;
}, new Set)];

console.log(result);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48