Retrieve the final elements of an array that share a common identifier

Retrieve the latest entries from the array with identical ids:

Input:

[{id:1,name:"Java"},{id:1,name:"JavaScript"},{id:1,name:"Python"},{id:1,name:"C++"},{id:2,name:"C"},{id:2,name:"Ruby"},{id:2,name:"Php"}]

Desired Output:

[{id:1,name:"C++"},{id:2,name:"Php"}]

Attempted Solution:

array?.reverse().filter( (ele, ind) => ind === array.findIndex((elem) => elem?.id === ele?.id))

However, it resulted in the incorrect output

[{id:1,name:"Java"},{id:2,name:"C"}]

Answer №1

To achieve this, a simple Array.reduce() can be used to create a map with the key being the id. The map is then converted into an array using Object.values():

const input = [{id:1,name:"Java"},{id:1,name:"JavaScript"},{id:1,name:"Python"},{id:1,name:"C++"},{id:2,name:"C"},{id:2,name:"Ruby"},{id:2,name:"Php"}];

const result = Object.values(input.reduce((acc, cur) => { 
    acc[cur.id] = cur;
    return acc;
}, {}))

console.log('Result:', result)

Alternatively, one could also utilize a Map and apply reduce once more:

const input = [{id:1,name:"Java"},{id:1,name:"JavaScript"},{id:1,name:"Python"},{id:1,name:"C++"},{id:2,name:"C"},{id:2,name:"Ruby"},{id:2,name:"Php"}];
const result = [...input.reduce((acc, cur) => {
    return acc.set(cur.id, cur);
}, new Map()).values()];
console.log('Result:', result);

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

Are you constantly receiving a -1 when trying to FindIndex value?

I am facing an issue with the following code: First, I retrieve the ID parameter from the URL: editUserId = this.route.snapshot.paramMap.get('id'); Next, I use FindIndex on an array of objects to find the index of an element that matches the ab ...

Transmit text from tinyMCE through AJAX in MVC architecture with PHP

I am currently facing an issue while trying to send POST data in the form of an array containing email elements such as subject and message. The problem arises when using tinyMCE for the subject part, which is not being sent through successfully. All other ...

The Java script is currently incompatible with Firefox, Internet Explorer 7, and Internet Explorer 6

Issues have been identified with the JavaScript code when running on Firefox, IE7, and IE6 (IE8 worked after applying getElementsByClassName.polyfill.js). Can anyone pinpoint the problem in the script that is causing these browsers to malfunction? (Chrome ...

JSON data not displaying correctly in bootstrap table

I've been grappling with this issue for hours now, but I'm struggling to get my bootstrap table populated correctly. Here's the snippet of my HTML: <html> <head> <link rel="stylesheet" href="https://code.jquery.com/ui/1.1 ...

Can a model be generated using Angular view values?

I am facing a challenge with a form that has complex functionality such as drag-and-drop, deleting groups of elements, and adding groups of elements. I want to leverage Angular for this task. The form is already rendered with original values set. <form ...

Attempting to create a pointer for a dynamically allocated character array

I'm attempting to create a char array on the heap and then set a pointer to it: char * head; char * customArray = new char[5]; This will allocate 5 bytes on the heap with characters, correct? head = &customArray; I am unable to do this ^ beca ...

Mapping prop passed to client component in NEXT 13: A step-by-step guide

Hello, I'm currently navigating through the Next 13 APP directory and have encountered a scenario where everything functions smoothly when I integrate the server component as shown below: const Tasks = async () => { const { tasks } = await getAll ...

The express-fileupload throws an error saying "ENOENT: unable to locate the file or directory at 'public/images/name.ext'"

I am encountering an error ENOENT: no such file or directory, open 'public/images/name.ext from express-fileupload. I have searched for solutions to this issue, but none of the ones I found seem to work for me. Here are two examples: No such file or d ...

In search of a JavaScript library that can help format strings to meet the requirements of JSON formatting

Utilizing jQuery ajax, I am transmitting updates from the client's browser to my server. However, I have noticed that there are certain characters not supported by JSON that require an additional "\" in front of each one to be properly sent. The ...

Delay in loading Jquery accordion due to value binding

I've noticed that my jquery accordion takes a significant amount of time to collapse when the page initially loads. After some investigation, I realized that the issue lies in the fact that there are numerous multiselect listboxes within the accordio ...

What are the consequences of excluding a callback in ReactJs that may lead to dysfunctionality?

<button onClick = { () => this.restart()}>Restart</button> While going through a ReactJs tutorial, I encountered a game page which featured a restart button with the code snippet mentioned above. However, when I tried to replace it with the ...

Adding an item to an object array in MongoDB can be achieved with the use of either the addToSet or push operators

I have a set of reviews in an array, and I am trying to implement addToSet functionality to add a review while ensuring that a user can only review once. Below is how my schema is structured: const sellerSchema = new mongoose.Schema({ user: { type: ...

Make sure the "Treat labels as text" option is set to true when creating a chart in a Google spreadsheet using a script

I am currently working on a script using Google Spreadsheet Apps Script interface and I need to set the marker for 'Treat labels as text' to true. Despite searching through App Script documentation, I couldn't find any specific mention of t ...

Discover how to obtain an access token using Yelp API V3 with JavaScript

Currently in the process of learning how to utilize this system, however there appears to be an issue with my code. $.ajax({ dataType: "POST", url: "https://api.yelp.com/oauth2/token", grant_type: "client_credentials", client_i ...

What is the process for implementing an image as the background instead of a color for each column in a Google chart?

I'm currently working with Google Chart and I have set up a column chart. However, I am looking to display a background image instead of a background color in each column. Is this achievable with Google Chart? If so, how can I accomplish this? If anyo ...

What is the method for using malloc to allocate arrays and 2D arrays with maximum length in C, while also accessing them efficiently?

I am currently developing a program that takes a text file as input, creates an index of the words within it, and then outputs this index both to a file and to the screen. The size of the input file could potentially be massive. However, I know for certai ...

Is there a method to verify the presence of an object within an array, and if it is not found, add it to the array?

In this quiz, I am collecting question numbers and answers to store in an array. The goal is to replace old answers with new ones if a person changes their response on the quiz. If a question hasn't been answered yet, it should be added to the array a ...

JQuery's find() method followed by length/size() is resulting in a return

I'm running into an issue with dynamically created divs. Here's how they are created: // Loop through and append divs to #result_main_search $("#result_main_search").append('<div class="singleresult_main_search"> <a href="http:// ...

Creating a custom bookmarklet that utilizes document.body.search()

I'm currently working on a bookmarklet that scans the body of a webpage for a specific text string and triggers a script when it finds a match. My code snippet document.body.search(); is resulting in an error message. [Error] TypeError: undefined is ...

Is it possible to send back both an Excel spreadsheet and a list of strings in a single response using .NET Core Web

From what I understand, when using C# and Excel, the file is transmitted as a binary array along with metadata to identify it as an Excel file in the frontend/browser: return File(resultStream.ToArray(), contentType); I'm wondering if there's a ...