I want to remove duplicated elements from an array of objects in React JS. My code is as follows :
let cars = [
{
id: 1,
make: "Volkswagen",
model: "Golf",
desc: "2.0 CR TDi Comfortline BMT"
}, {
id: 2,
make: "Audi",
model: "Q3",
desc: "2.0 CR TDi Comfortline BMT"
}, {
id: 3,
make: "Volkswagen",
model: "Passat CC",
desc: "2.0 CR TDi Comfortline BMT",
}, {
id: 4,
make: "Volkswagen",
model: "Golf",
desc: "1.9 TDI",
}, {
id: 5,
make: "Audi",
model: "Q5",
desc: "2.0 CR TDi Comfortline BMT",
}, {
id: 6,
make: "Volkswagen",
model: "Golf",
desc: "2.0 CR TDi",
}
]
class Test extends React.Component {
getTotalModels(model){
return cars.filter(c => c.model === model).length;
}
getTotalMakes(make){
return cars.filter(c => c.make === make).length;
}
render(){
return (
<div>
{cars.map(c => {
return (
<div key={c.id}>
<div className="make">{c.make} ({this.getTotalMakes(c.make)})</div>
{cars.filter(j => j.make === c.make).map(i => {
return <div className="models">{i.model} ({this.getTotalModels(i.model)})</div>
})}
</div>
)
})}
</div>
)
}
}
React.render(<Test />, document.getElementById('container'));
The result that I get is :
Volkswagen (4)
Golf (3)
Passat CC (1)
Golf (3)
Golf (3)
Audi (2)
Q3 (1)
Q5 (1)
Volkswagen (4)
Golf (3)
Passat CC (1)
Golf (3)
Golf (3)
Volkswagen (4)
Golf (3)
Passat CC (1)
Golf (3)
Golf (3)
Audi (2)
Q3 (1)
Q5 (1)
Volkswagen (4)
Golf (3)
Passat CC (1)
Golf (3)
Golf (3)
The result that I want is :
Volkswagen (4)
Golf (3)
Passat CC (1)
Audi (2)
Q3 (1)
Q5 (1)
I tried with lodash uniq function, but it didn't work.