Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

381
Views
JavaScript: eliminar duplicados de una matriz de objetos

Tengo una matriz de datos que se parece a esto.

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

Quiero filtrar el elemento cuyo type ya existía. Y quiero mantener el primer elemento.

Por ejemplo, mantenga Apple en lugar de Orange

 data = [ { "name": "Apple", "type": "Fruit"}, { "name": "Cabbage", "type": "Vegetable"} ]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Usando Array#filter , puede iterar sobre la matriz mientras actualiza un Set para realizar un seguimiento de los tipos agregados:

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

about 4 years ago · Juan Pablo Isaza Report

0

1) Puede filtrar el resultado si el type ya no está presente en dict usando el filter y Set como:

 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) También puede usar for..of y Set como:

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!