2

I have an array of data which looks like this.

data = [ 
  { "name": "Apple", "type": "Fruit"}, 
  { "name": "Cabbage", "type": "Vegetable"} , 
  { "name": "Orange", "type": "Fruit"} 
] 

I want to filter out the element which its type already existed. And I want to keep the first element.

E.g. keep Apple instead of Orange

data = [ 
  { "name": "Apple", "type": "Fruit"},
  { "name": "Cabbage", "type": "Vegetable"}
]
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
hiruzxn
  • 60
  • 1
  • 8
  • 1
    Does this answer your question? [Get all unique values in a JavaScript array (remove duplicates)](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates) – derpirscher Nov 18 '21 at 06:33
  • What have you attempted till now? A loop logic will help you to achieve this. Where are you stuck with? – Nitheesh Nov 18 '21 at 06:36
  • @derpirscher the question might look the same but it's actually not. That solution does not answer my question because the array I have is an object array. Thanks for you help tho. – hiruzxn Nov 18 '21 at 06:53
  • @Nitheesh I am trying using .filter instead of loop but it's not working for me. – hiruzxn Nov 18 '21 at 06:54
  • @Jonnie Please accept the relavent answer and close this thread. – Nitheesh Nov 18 '21 at 07:19

2 Answers2

2

Using Array#filter, you can iterate over the array while updating a Set to keep track of types added:

const data = [ { "name": "Apple", "type": "Fruit"}, { "name": "Cabbage", "type": "Vegetable"}, { "name": "Orange", "type": "Fruit"} ];

const typeSet = new Set();
const res = data.filter(({ type }) => {
  if(typeSet.has(type)) return false;
  typeSet.add(type);
  return true;
});

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

1) You can filter the result if type already not present in dict using filter and Set as:

data.filter((o) => (dict.has(o.type) ? false : dict.add(o.type, true)))

const data = [
  { name: "Apple", type: "Fruit" },
  { name: "Cabbage", type: "Vegetable" },
  { name: "Orange", type: "Fruit" },
];

const dict = new Set();
const result = data.filter((o) => (dict.has(o.type) ? false : dict.add(o.type, true)));
console.log(result)

2) You can also use for..of and Set as:

const data = [
  { name: "Apple", type: "Fruit" },
  { name: "Cabbage", type: "Vegetable" },
  { name: "Orange", type: "Fruit" },
];

const dict = new Set(), result = [];

for (let o of data) {
  if (!dict.has(o.type)) {
    result.push(o);
    dict.add(o.type);
  }
}

console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42