Home > Software design >  discard duplicates of fetched makes in array of objects
discard duplicates of fetched makes in array of objects

Time:07-28

So I want to populate react-select with a Make category dropdown. I want to have all makes in a dropdown like categories and to filter a list of cars when a make is selected. This is the result of maped Array.

enter image description here

The makes are repeting themselves. How do I discard duplicates? Here is my code:

import React from 'react' import './FilterSideBar.css' import Select from 'react-select';

const colourStyles = {   control: (styles) => ({ ...styles, backgroundColor: "transparent" }),   option: (styles, { isDisabled })
=> {
    return {
      ...styles,
      backgroundColor: isDisabled ? "transparent" : "grey" ,
      color: "#FFF",
      cursor: isDisabled ? "not-allowed" : "default"
    };   } };

const FilterSideBar = ({carsList}) => {   const options = carsList.map((car) => {
    return {
      value: car.make,
      label: car.make
    }   })

    return (
            <> <Select  options={options} styles={colourStyles} isSearchable={false}/>
            </>
        )
    }

export default FilterSideBar

And here is json example that Im fetching from:

>  [{"id":"14","make":"KIA","model":"Ceed","year":"2017","month":"12","body":"Kombi
> \/ Family
> Van","mileage":"76000","fuel":"Diesel","transmission":"Schaltgetriebe","condition":"Gebrauchtwagen","drivetrain":"Vorderrad","engine":"1582"},
> {"id":"15","make":"BMW","model":"750","year":"2017","month":"12","body":"Limo","mileage":"24000","fuel":"Diesel","transmission":"Schaltgetriebe","condition":"Gebrauchtwagen","drivetrain":"Ruckrad","engine":"5000",
> {"id":"16","make":"KIA","model":"Ceed","year":"2019","month":"05","body":"Kombi
> \/ Family
> Van","mileage":"120000","fuel":"Diesel","transmission":"Schaltgetriebe","condition":"Gebrauchtwagen","drivetrain":"Vorderrad","engine":"1700"]

CodePudding user response:

const distinctBy = (arr, f) => {
  return arr.filter((a, i) => arr.findIndex((b) => f(a) === f(b)) === i);
}

const options = carsList
  .map((car) => {
    return {
      value: car.make,
      label: car.make
    };
  })
 
 const distinctOptions = distinctBy(options, car => car.value)
  • Related