Utilize Autocomplete component from Material UI to sift through distinct option values

Looking to implement unique options in the dropdown menu of an Autocomplete component from Material UI based on a specific property within a list of objects.

The current issue is that duplicate values are appearing in the dropdown, like

['Color1', 'Color2', 'Color1', 'Color2']
, instead of displaying only unique values such as ['Color1', 'Color2'].

List of objects being used:

options = [
    {
        id: 1,
        name: 'Name1',
        color: 'Color1'
    },
    {
        id: 1,
        name: 'Name2',
        color: 'Color2'
    },
    {
        id: 1,
        name: 'Name3',
        color: 'Color1'
    },
    {
        id: 1,
        name: 'Name4',
        color: 'Color2'
    },
]

Here's the code for the Autocomplete component:

<Autocomplete
    freeSolo
    value={initialTasting}
    options={options}
    getOptionLabel={option => option.color}
    filterOptions={(options, state) => options}
    onChange={(e, value) => {setFieldValue('color', value.color)}}
    renderInput={params => (
        <TextField
            {...params}
            label={'Color'}
            variant='outlined'
            margin='dense'
            fullWidth
        />
    )}
/>

Omitted additional code due to length, which includes Formik, Yup validations, and other child components.


Having trouble implementing the desired unique option functionality using the filterOptions prop. Any assistance with JavaScript would be greatly appreciated!

Thank you in advance.

Answer №1

Have you considered updating your options array in a similar way to this?

function filterUniqueListBy(arr, property) {
    return [...new Set(arr.map(item => item[property]))]
}

const uniqueOptions = filterUniqueListBy(options, 'type');

...and then utilize uniqueOptions as the options parameter for the <Dropdown /> component

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to activate the :active pseudoclass by pressing the 'enter' key on the keyboard using solely CSS?

The CSS: a:focus { opacity: .75 } a:active { transform: translateY(4px) } The purpose: When keyboard users tab to the link, the :focus style serves as a visual indicator Upon pressing the enter key to activate the link, the :active style provides ...

Unable to retrieve object element in angular

weatherApp.controller('forecastController', ['$scope','weatherService','$resource','$log', function($scope,weatherService,$resource,$log){ var cnto =3; $scope.forecastholder = weatherService.holder; $scope ...

Can we display an express view in response to a WebSocket event?

My goal is to display an express view within a websocket event as shown below: socket.on('name', function () { //prompt the client to render a specific express view }); ...

Creating a Recursive Facebook Page Data Scraper using Selenium and Node.js

I am trying to iterate through an array of Facebook page IDs and retrieve the code from each event page. However, I am encountering a problem where I only get the code of the last page ID in the array repeated multiple times. For example, if there are 3 ID ...

Successful execution occurring prior to beforeSend in a Cordova iOS application utilizing jQuery Ajax

After making some changes to the HTML of the login button, I encountered an issue where the alert was being triggered before the button's HTML had updated when testing on my iPhone using a Cordova-built app. Strangely, this problem did not occur when ...

Challenges encountered when retrieving parameters from union types in TypeScript

Why can't I access attributes in union types like this? export interface ICondition { field: string operator: string value: string } export interface IConditionGroup { conditions: ICondition[] group_operator: string } function foo(item: I ...

Step-by-step guide on redirecting to a different page following a successful POST API call using Jquery

I have the code below in my JavaScript file. $scope.addLookupAction = function () { $("#importForm").attr("action", 'xyz.com'); success:function(response) { $log.info("Redirecting to lookup home page"); ...

Building a Dynamic Grid Design using Material-UI in a React App

I am currently diving into the MUI grid system for the first time and feeling a bit lost. My goal is to create a responsive vertical grid layout, and I have attached an example image for reference. Below is my attempt using the default MUI component. I w ...

Is there a way to switch the main image by clicking on different thumbnails in a sidebar using javascript/jQuery

Currently on my page, I have a large plot created with jqplot along with a sidebar containing several smaller plots. I am trying to find a way to dynamically change the large plot based on which of the smaller plots the user clicks on, without needing to ...

What occurs in the event of a server crash following the scheduling of a task using cron?

Imagine I set a task to take place at time t2 in the future, where t1 < t2 < t3 If the server crashes at time t1, will the scheduled task still run if the server is restarted before t2 (t1 < t < t2)? What happens if the server crashes at t1 a ...

Transmitting Filter Choices as an Object for Retrieving Multiple Values within an Angular Application

In my Angular application, I have a function that takes user selections for various filter types and sends a request to the API to retrieve filtered data based on those selections. Each filter type returns values in an array format, allowing users to selec ...

Display JSON content in a div depending on the selected option value

Seeking a more efficient way to load data from a JSON file based on the user-selected option. Currently, I am using multiple else if statements for each state, but it feels repetitive and cumbersome. Is there a better approach? Here's a snippet of my ...

Bringing in a feature within the Vue 3 setup

At the moment, I am attempting to utilize a throttle/debounce function within my Vue component. However, each time it is invoked, an error of Uncaught TypeError: functionTD is not a function is thrown. Below is the code snippet: useThrottleDebounce.ts imp ...

"Improprove your website's user experience by implementing Material UI Autocomplete with the

Recently, I experimented with the Autocomplete feature in Material UI. The focus was on adding an option when entering a new value. You can check out the demo by clicking on this link: https://codesandbox.io/s/material-demo-forked-lgeju?file=/demo.js One t ...

Error in Typescript: Function expects two different types as parameters, but one of the types does not have the specified property

There's a function in my code that accepts two types as parameters. handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) { e.stopPropagation(); const newValue = this.computeValuesFromPosition(e.detail.x ...

Error: The request does not have the 'Access-Control-Allow-Origin' header

As a beginner in post requests, I've been encountering an error when attempting to make a post request. Despite searching for solutions, the answers are too complex for me to grasp how to adjust my code to resolve it. var url = 'http://unturnedb ...

Is it possible for multiple queries executed within a websql transaction to be run concurrently?

An informative tutorial online demonstrates the following transaction: db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")&ap ...

Issues persist with AngularJS integration using Modernizr

Incorporating AngularJS and Modernizr, I aim to identify media queries and trigger a function whenever the window or viewport is resized. My goal is to control element visibility based on whether the user is on a desktop or mobile device - certain elements ...

Facing an issue with displaying a component error in a mat-form-field in Angular 9

I am looking to develop a shared component for displaying errors in Angular Material. Here is my shared component pfa-share-error: <mat-error *ngIf="fieldErrors(fieldName).required && fieldErrors(fieldName)"> Required </mat-err ...

JavaScript's failure to properly handle UTF-8 encoding

Here is a snippet of code that I found on Stack Overflow and modified: <?php header('Content-Type: text/html; charset=ISO-8859-1'); $origadd = $_SESSION["OriginAdd"] // $_SESSION["OriginAdd"] contains the value "rueFrédéricMistral"; echo $o ...