How to retrieve distinct items from an array using Javascript

If I have the following array of objects:

const arr = [{ id: 'A', version: 0, name: 'first' },
             { id: 'A', version: 1, name: 'first' },
             { id: 'B', version: 0, name: 'second' },
             { id: 'A', version: 2, name: 'first' },
             { id: 'B', version: 1, name: 'second' }];

I want to use this array as input for creating two drop-down menus.

The first drop-down menu should display only the values A and B.

To achieve this, I can do the following:

const firstDropdownOptions = [...new Set(arr.map((el) => el.id))];

However, this code will only return ['A', 'B'] without any additional information about the properties of each object.

It would be more useful if the output looked like this:

[{ id: 'A', version: '0', name: 'first' }, { id: 'B', version: '0', name: 'second' }]

Do you have any suggestions on how to modify the code to return the desired array format?

Answer №1

You can easily group by the id and dynamically set the options for the second dropdown based on the selection made in the first dropdown.

const
    setOptions = id => groups[id].forEach(o => {
        const option = document.createElement('option');
        option.value = o.version;
        option.innerHTML = o.version;
        second.appendChild(option);
    });

    data = [{ id: 'A', version: 0, name: 'first' }, { id: 'A', version: 1, name: 'first' }, { id: 'B', version: 0, name: 'second' }, { id: 'A', version: 2, name: 'first' }, { id: 'B', version: 1, name: 'second' }],
    first = document.createElement('select'),
    second = document.createElement('select'),
    groups = data.reduce((r, o) => ((r[o.id] ??= []).push(o), r), {});

document.body.appendChild(first);
document.body.appendChild(document.createTextNode(' '));
document.body.appendChild(second);

Object.keys(groups).forEach(k => {
    const option = document.createElement('option');
    option.value = k;
    option.innerHTML = k;
    first.appendChild(option);
});

setOptions('A');

first.addEventListener('change', function (event) {
    let i = second.options.length;
    while (i--) second.remove(i);
    setOptions(first.value);
});

Answer №2

After some experimentation, I discovered a concise way to address this issue:

const uniqueValues = array.filter((element, idx, self) => { 
    return self.findIndex(item => item.id === element.id) === idx
});

Answer №3

Insight : By utilizing the array.map() method to return only the id, you are able to obtain unique Id's [A, B] in a separate array. If you wish to retrieve all other properties, you will need to implement a condition to verify if version === 0.

Interactive Example :

const arr = [{ id: 'A', version: 0, name: 'first' },
             { id: 'A', version: 1, name: 'first' },
             { id: 'B', version: 0, name: 'second' },
             { id: 'A', version: 2, name: 'first' },
             { id: 'B', version: 1, name: 'second' }];
             
const firstDropdownData = arr.filter((obj) => obj.version === 0);

console.log(firstDropdownData);

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

Import several image files using AngularJS

I recently came across a helpful tutorial that demonstrates how to upload pictures from your local computer using AngularJS directives. As a newcomer to Angular, I followed the instructions but now I'm stuck on modifying it to display the selected ima ...

Accessing Key-Value Pairs in PHP from a JSON Encoded Array

Is there a way for me to retrieve the LocalId Key Value in Php? This particular Array is Json Encoded. {"0":{"kind":"identitytoolkit#VerifyPasswordResponse","localId":"u0iuiF09idQ1pEl0oJTfElqTtXr1"}} ...

Navigating on Blogger can be a tricky task when it comes to searching and

I recently added a Table to my blogger post, along with an input form for readers to easily search data. After finding the code on W3Schools (link here), I implemented it successfully. However, I am looking to make some improvements. Here is my question: ...

After a short delay, make sure to open a new tab when clicking to bypass any popup blockers without relying on Ajax technology

Before you downvote, please consider my rationale. I am in the process of developing a web-based educational project that includes an art section. When a user clicks on a button, an element containing a picture of an art piece appears. I then want to open ...

I am curious about the inner workings of the `createApplication()` function in the ExpressJS source code. Can you shed some light on

My goal is to deeply comprehend the inner workings of the Express library, step by step. From what I gather, when we import and invoke the 'express()' function in our codebase, the execution flow navigates to the ExpressJS library and searches fo ...

What are the steps to retrieve JSON data and display it using an unordered list in an HTML document?

My JSON data structure looks like this: { "fID": "00202020243123", "name": "John Doe", "List": ["Father", "Brother", "Cousin"] } When I render this JSON element in my model and view it in the HTML, everything works fine. However, when I try t ...

Detecting Android devices

Issue: My website functions properly on desktop but has a problem with the carousel images skewing on iPhones. To address this, I created a separate CSS styling for iPhone devices and used a JavaScript function found online to detect iPhones and iPads. Un ...

Place a div element directly into a specific cell within the table

How can I place the following div <div class="inner"> <p>The first paragraph</p> <p>The second paragraph</p> </div> into a specific cell within a table? I am open to using either plain JavaScript or jQuery, althou ...

Transferring a value via AJAX that has been modified by a previous AJAX call

In my form, users input values which are used to calculate a result. The calculation is performed through AJAX calls triggered by onchange events on the user-edited fields. This process works as expected. However, there is a hidden field that also gets up ...

Get JSON data through AJAX using two different methods

Help needed: JSON request issue with XMLHttpRequest var xhr = new XMLHttpRequest(); function elenco_studenti() { var url = "/controller?action=student_list"; xhr.responseType = 'text'; xhr.open("GET", url, true); xhr.onreadystat ...

What could be causing jQuery document ready to restrict access to global variables?

Currently, I am working on a project that involves three separate JavaScript files (example1.js, example2.js, and example3.js) being scripted into a single HTML file (index.html). These JS files are responsible for making an API call and manipulating the r ...

Revamping array elements in React

Once I added an element to the array, I needed to update this array by doubling all elements except for the one that was just added. Despite trying setArray([]) before retrieving the array from the database, it didn't seem to work... const [array, se ...

loading xml data into a table partially using jquery

Currently, I am utilizing AJAX to load and parse XML data. I have constructed a table where I am inserting the data from the XML using a loop. The issue lies in the fact that only around 3000 rows are being inserted into the table even though the XML conta ...

performing asynchronous iteration with HTTP PUT requests

I'm attempting to send multiple HTTP PUT requests to my server, but I am only able to successfully send one JSON object to the database. What could be missing in my code? var data1 = JSON.stringify(require('./abc.json')), data2 = JSON ...

Is it possible to generate an array of strings from the keys of a type or interface?

Imagine a scenario where we have a type or interface defined as NumberLookupCriteria: type NumberLookupCriteria = { dialCode: string; phoneNumber: string; } or interface NumberLookupCriteria { dialCode: string; phoneNumber: string; } Is there a w ...

Ensuring the correct data type for a member variable within a two-dimensional array

I am facing compilation errors as I struggle to correctly define a member variable in my class as a pointer to a 2D array. While there are plenty of examples on this board that show how to receive pointers to 2D arrays and access the data immediately, my g ...

Verify whether a dependency is being passed into an Angular component

As mentioned in a discussion about IE caching issues, Internet Explorer tends to cache things when using ajax with AngularJS, causing potential problems. You can find a helpful solution to this problem here. Given that we have multiple angular apps on our ...

The AJAX validation process fails to run prior to the execution of the login PHP script

My attempt to implement AJAX for form validation is not successful and I'm unsure why. Despite my efforts, the form still redirects to login_action.php instead of performing the AJAX validation as intended. I have designed a modal login form and wish ...

Issue with handling click events on action column in Datatable using jQuery

Utilizing jquery datatable with an action column containing "edit" and "delete" links. The table populates correctly, but encountering an issue when trying to open a bootstrap modal form upon clicking the edit button within the table. However, the modal do ...

Adding query parameters to the end of every link on a webpage

Wondering how to automatically add GET values to the end of each anchor href on a webpage? For instance, if you input google.com?label=12&id=12 I want to ensure that "?label=12&id=12" gets added to the end of every single href in an anchor tag on ...