Utilize the Set data structure to eliminate duplicates from an array while retaining the item with

Looking for help with this array:

array = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 
'apple'}]

I want to eliminate objects with duplicated "name" property while retaining the highest id for each unique object, resulting in:

newarray = [ {id: 2, name: 'banana'}, {id: 3, name: apple}]

This is what I have attempted so far:

array = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 
apple}]

newarray = Array.from(new Set(array.map(x => x.id)))
                 .map(id => {
                   return {
                     id: id,
                     name: array.find( s => s.id === id).name
})

The current result obtained is:

newarray = [ {id: 2, name: 'banana'}, {id: 1, name: apple}]

While duplicate objects are removed, the issue lies in not getting the highest id for each remaining object.

Appreciate any suggestions on how to achieve the desired outcome. Thank you!

Answer №1

To achieve the desired outcome, I recommend utilizing the `reduce` method instead. This will allow you to reduce an array into an object that is indexed by name, with each value being the associated `id` / `name` objects. It's important to note that if an object already exists at a given name, only reassign it if the new object's ID is higher:

const array = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 
'apple'}];

const newArray = Object.values(
  array.reduce((a, item) => {
    const { name } = item;
    if (!a[name] || a[name].id < item.id) {
      a[name] = item;
    }
    return a;
  }, {})
);
console.log(newArray);

Answer №2

I successfully utilized a combination of map, filter, and reduce techniques!

Explanation can be found within the code comments.

Check out the demo below

var array = [{
  id: 1,
  name: 'apple'
}, {
  id: 2,
  name: 'banana'
}, {
  id: 5,
  name: 'banana'
}, {
  id: -9,
  name: 'pear'
}, {
  id: 3,
  name: 'apple'
}, {
  id: -3,
  name: 'pear'
}];

/*
  1 - it creates a Set from mapping original array into a list of names
  2 - it then maps it back into the objects but this time 
     2.1 - it filters the original array to elements with only matching names
     2.2 - and then it reduces the id to the highest value
*/
var filteredArray = Array.from(new Set(array.map(x => x.name))).map(e => {
  return {
    id: array.filter(function(el){
      return el.name == e;
    }).reduce((curr, next) => curr.id > next.id ? curr.id : next.id, 0),
    name: e
  }
});

console.log(filteredArray);

Answer №3

If you want to achieve the desired outcome, you can implement a solution using the sort and reduce functions.

Object.prototype.use = function(func) {
  return func(this)
}

var result = [{
    id: 1,
    name: 'apple'
  }, {
    id: 2,
    name: 'banana'
  }, {
    id: 3,
    name: 'apple'
  }]
  .sort((a, b) => b.id - a.id)
  .reduce((obj, data) => obj[data.name] ? obj : ({ ...obj, [data.name]: data }), {})
  .use(output => Object.values(output))

console.log(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

Guide to making axios/api calls in a Nativescript mobile application

In my development process, I am working on creating a small application using Nativescript-vue. This application requires backend functionality that is built on the laravel framework for making API calls to retrieve relevant data. For example, when a user ...

What is causing the click event to not fire in this straightforward jsfiddle demonstration?

While attempting to create a demonstration on jsfiddle, I encountered an issue where the click event for the toggle button is not firing. An error message stating myclick is not defined appears. I have researched other solutions that suggest using the No ...

Executing various axios requests to retrieve diverse data and populating multiple sections of the user interface in React Native

I am struggling to display various categories of movies on the same screen, such as "POPULAR MOVIES", "RECOMMENDED MOVIES", and "NEWEST MOVIES". I have been able to retrieve data for the "POPULAR MOVIES" section using an API call, but I'm unsure of th ...

Verify whether an element in the array is being referenced in the file

In an attempt to check if certain array elements are being used, I have the following code. Please correct me where necessary: Firstly, I open the myclass.css file and iterate through each line to add all selectors that start with a hashtag or dot into an ...

What is the best way to send a JavaScript variable to PHP for storage in a WordPress database?

I am currently in the process of developing a star rating system within Wordpress and am looking to store the rating data in the Wordpress database. To achieve this, I have saved the star rating PHP code as a template within my Wordpress theme folder. Belo ...

Change the background color of all cells in a Bootstrap table by hovering over a single cell

Here is the code for a bootstrap table: <body leftmargin="0" topmargin="0" bgcolor="#ffffff" marginheight="0" marginwidth="0"> <div class="container-fluid h-100"> <div class="row float-right align-items-center" style="height: 5%;"> ...

Inaccurate Guild Member Filtering

Recently, I've been working on creating a unique member counter for my server. The goal is to accurately count the total number of members in the server, excluding bots, and counting only bots as well. However, when I attempt to display these counts i ...

React Switch not displaying various pages correctly

After creating a new component to switch between pages on my React app, I encountered an issue where the HomePage renders correctly when entering the site, but clicking on navlinks does not work. Additionally, when trying to access the url /contacto, ins ...

Troubleshooting issue: Asynchronous functionality not working with Ajax.BeginForm

Struggling to grasp ASP.Net MVC and facing challenges with using Ajax.BeginForm to update a partial view asynchronously. Here's the code snippet in the view for the action: @using (Ajax.BeginForm( new AjaxOptions { ...

Issue: StaticInjectorError(DynamicTestModule)[CityService -> Http]: Http provider not found

I am working on a service that retrieves all cities from a web service. @Injectable() export class CityService { constructor(private http: Http, private router: Router, private auth: AuthService) { } public getAllCity(): Observable<City[]> { ...

Angular Material 2 with Customized Moment.js Formatting

Is there a way to display the year, month, day, hours, minutes, and seconds in the input field of my material datepicker? I have successfully customized the parse() and format() methods in my own DateAdapter using native JavaScript objects. Howe ...

Creating a single page application in Angular2+ using JSON data

I am looking to create an Angular JS application using the provided JSON structure: { name: 'App Name', pages: [ { name: 'Home', url: '/', layout: { type:'HTMLElement' tag:'div ...

What could be causing media queries to not update values even after being changed through JavaScript?

I have a simple navigation bar on my website, featuring links to different subpages. To enhance the user experience on mobile devices, I added a hamburger menu icon that is displayed on smaller screens. The links in the navigation bar are hidden using CSS ...

What steps can I take to make my animation work in the opposite direction as well?

I'm currently working with an angular slider that is set to TRUE/OPEN by default. The issue I am facing is that while I am able to slide it using angular animations in one direction, I am unable to see the transition when sliding it back. Any assistan ...

Is there a way to prevent the use of any keys other than letters and numbers in the search input field of a datatable, such as function keys or shortcut keys?

jQuery Query: Is it possible to trigger the search function only when alphabet and number keys are typed? For DataTables, global searching should only start when at least 3 characters have been entered. $(document).on('draw.dt','.dataTable ...

What is the process for obtaining the number of video views using the YouTube API?

I have a straightforward question: How can I retrieve the number of video views using the YouTube API? Although the task is simple, I need to perform this query on a large number of videos frequently. Is there a way to access their YouTube API in order to ...

Switch up your text display using JQuery and toggle between different texts

I have implemented a jQuery script to toggle the display of certain paragraphs when the "More" link is clicked. However, I am facing an issue where the link always displays "More" even after the content has been expanded. I want it to change to "Less" once ...

Obtaining Data from an XML Node Using AJAX

Trying to extract statistics from my XML based on a specific name request, but encountering issues with my JavaScript functionality. XML data: <player> <forward><name>Joe</name><stats>45</stats></forward> <f ...

Encountering a CastError in Mongoose validation where the value fails to cast to undefined

I encountered a forbidden message while attempting to save data into the database. CastError: Cast to undefined failed for value [ {"product":{"supplierId":{"undefined":"rfytr"}}}, {"product":{"supplierId":{"$empty":"rfytr"}}} ] at path "condition" ...

Encountering issues with running NPM on my Ubuntu server hosted on Digital Ocean

After successfully installing node (nodejs), I encountered a persistent error when attempting to use NPM. Despite researching the issue extensively and trying different solutions, I have been unable to resolve it. Here is the error message displayed in th ...