Remove the lesser of two duplicate items from the list by comparing their count keys

Here is a challenge I encountered with a grocery list that required filtering out duplicates and only keeping the duplicate with the higher count, while also retaining non-duplicate items. I managed to achieve this through trial and error programming, but I am eager to discover a more efficient solution. The code below describes the steps I took and my thinking process. If anyone knows of a better approach to solving this problem, I am open to learning.

var groceryList = [
  {
    item: "Bananas",
    count: 4
  },
  {
    item: "Bananas",
    count: 3
  },
  {
    item: "Brussel Sprouts",
    count: 2
  },
  {
    item: "Bacon",
    count: 100
  },
  {
    item: "Beans",
    count: 19
  },
  {
    item: "Beans",
    count: 5
  }
]

const seen = {}
const newList = []
var removeDups = []
const list = groceryList.map(function(item) {
  // Add new items to seen object and newList array
  if (!seen[item.item]) {
    seen[item.item] = item
    newList.push(item)
  }
  // Handle duplicates
  else if (seen[item.item]) {
    // Filter out duplicates from newList
    removeDups = newList.filter(function(listItem) {
      if (listItem.item == item.item) {
        console.log('matched');
      } else {
        return true
      }
    })

    // Keep only the item with higher count
    if (seen[item.item].count > item.count) {
      removeDups.push(seen[item.item])
    } else {
      removeDups.push(item)
    }
  }
})

console.log(removeDups);

Answer №1

Utilizing the reduce method allows for a concise way to convert an array into a different format, such as another array or an object, even when the input and output items do not have a one-to-one relationship:

var groceryList=[{item:"Bananas",count:4},{item:"Bananas",count:3},{item:"Brussel Sprouts",count:2},{item:"Bacon",count:100},{item:"Beans",count:19},{item:"Beans",count:5}]
const filteredListObj = groceryList.reduce((a, { item, count }) => {
  // this is a new item, or a duplicate with a greater quantity:
  if (!a[item] || a[item].count < count) a[item] = { item, count };
  return a;
}, {});
const filteredList = Object.values(filteredListObj);
console.log(filteredList);

Answer №2

One way to optimize memory usage is by utilizing a hash table to store original objects instead of creating new ones.

var groceryList = [ { item: "Bananas", count: 3 }, { item: "Bananas", count: 4 }, { item: "Brussel Sprouts", count: 2 }, { item: "Bacon", count: 100 }, { item: "Beans", count: 19 }, { item: "Beans", count: 5 }], 
    hash = Object.create(null),
    uniques = groceryList.reduce((r, o) => {
        if (!(o.item in hash)) {
            hash[o.item] = r.push(o) - 1;
        }
        if (r[hash[o.item]].count < o.count) {
            r[hash[o.item]] = o;
        }
        return r;
    }, []);
    
console.log(uniques);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

To ensure uniqueness and override values if necessary, consider creating a map or object with the item name as the key.

var shoppingList = [
  {
    item: "Apples",
    count: 5
  },
  {
    item: "Apples",
    count: 8
  },
  {
    item: "Carrots",
    count: 3
  },
  {
    item: "Cheese",
    count: 12
  },
  {
    item: "Oranges",
    count: 15
  },
  {
    item: "Oranges",
    count: 20
  }
];

let updatedList = shoppingList.reduce((map, obj) => {
   if (!(obj.item in map) || (obj.item in map && map[obj.item] < obj.count)) {
      map[obj.item] = obj.count;
   }
   return map;
}, {});
updatedList = Object.keys(updatedList).map(item => ({ item, count: updatedList[item] }));
console.log(updatedList);

Answer №4

Here is a more straightforward answer that leverages the unique keys of an object and utilizes Math.max to select the higher count for each item.

let updatedList = [];
for(let index in groceryList){
  let count = updatedList[groceryList[index].item] || 0;
    updatedList[groceryList[index].item] = Math.max(groceryList[index].count, count);
};

console.log(updatedList);

Check it out on Fiddle: https://jsfiddle.net/w2szmmya/

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

What steps can be taken to halt an ongoing AJAX call and initiate a new one with different parameters?

I recently implemented an ajax call using the jQuery.everyTime() function. The setup involves a combo box where users can select different graph names, triggering dynamic calls to an ajax function that returns JSON data and populates a chart in the View ev ...

Selecting items from a list at random using the power of math.random() and math.floor()

When attempting to randomize the popping of elements in a list stored in the baby variable, only baby[1] is being popped. How can I make it pop random elements? <body> <h1 id="1">bebe</h1> <h1 id="2">t ...

Navigating through events within React

I'm working on creating a login page, where upon clicking the submit button it should navigate to the Dashboard page. However, I seem to be encountering an issue with my code. After entering login details and clicking on the login button, the details ...

Enhance your design with dynamic hover effects

I need assistance with modifying the menu structure generated by Wordpress. Specifically, I want to change the background of #header-nav li ul.children li a when #header-nav li ul.children li ul.children li a:hover is active. Could someone provide guidanc ...

A specialized Discord bot designed to capture and forward all direct messages to a designated webhook

I am looking to develop a bot using discord js v13 that can intercept all DM messages and send them to a webhook. Additionally, I want the bot to send a reply back to the sender once the admin gives the command '/reply [text]'. I am unsure of how ...

Barrier Preventing My Access to the Page

Currently, I am working on a vue page that includes a navigation-guard. This particular page serves as an 'Update Details' section where I have implemented the use of beforeRouteLeave. The purpose of this setup is to display a warning modal if an ...

Execute a function and simultaneously input data into MySQL using Node JS

Is there a way to simultaneously insert data from multiple external data sources into a database? I have several APIs/Endpoints that provide the same dataset, and I want to insert them all at once. For instance: Right now, my code loops through each API ...

navigating to the start of a hyperlink

I'm having issues with scrolling to anchors and encountering 3 specific problems: If I hover over two panels and click a link to one of them, nothing happens. When I'm on section D and click on section C, it scrolls to the end of section C. ...

TinyMCE - The control with the name 'content' is considered invalid and cannot receive focus

I am utilizing TinyMCE 4 and here is the code snippet for it: <script type="text/javascript" src="//cdn.tinymce.com/4/tinymce.min.js"></script> <script> tinymce.init({ selector: 'textarea[name=content]', ...

Having issues with templateURL not working in AngularJS routeProvider

I've been experimenting with ngRoute and I'm facing an issue with templateURL not working as expected. The functionality works perfectly except for when I attempt to use templateURL. Here are the 4 files involved: test.html <p>{{test}}&l ...

Can the layout created with JqueryMobile be used on both web and mobile platforms?

I develop websites using php for the backend and HTML/CSS for the frontend. Currently, the need to make my website mobile-friendly has arisen. I am contemplating utilizing JqueryMobile but I'm uncertain if the same layout will work for both desktop an ...

Determine if a cell is editable within the `renderEditCell` function by using MUI

I am working with a MUI data grid that contains different cell types. I am currently seeking a way to implement user permission-based editing for cells in the grid. However, I only want the permission testing to occur when a user attempts to edit a cell, r ...

Obtain real-time information from an object using React

After developing an app using React, I encountered a scenario where I needed to work with data from an API. Here is the object structure: let currency = { "success": true, "timestamp": 1648656784, "base": "EUR", &quo ...

Ways to rejuvenate an angular component

I am in the process of developing a mobile application using ionic 4. The app supports two languages, namely ar and en. The menu drawer is a pre-built component included within the app. In order to ensure that the drawer component displays the correct sty ...

When using v-for to render components and <selection>, is there a way to customize it for just one specific instance of the component?

How can I modify the selection in each instance separately when rendering elements of an array obtained from the backend using v-for? Currently, changing one selection affects all instances due to the v-model. Is there a way to target only one selection ...

Ways to serve JSON response following a 400 error code

After a user submits incorrect form details, such as an invalid username or blank email address, I make an Ajax request to my REST API. The response data I receive is structured as follows: HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: applicati ...

Using JQuery to Enhance the Highlight Effect: Tips and Tricks

Exploring the functionality of the "highlight" JQuery effect: http://docs.jquery.com/UI/Effects/Highlight You have the ability to modify the background color of any DIV element with a fade in/out effect. However, the provided example demonstrates trigge ...

Is it possible to combine the outcomes of a SQL query that produces numerous entities with identical identifiers?

Currently working on my first Node.js API project. Within the '/posts' endpoint, I am receiving data in this format: [ { "POST_ID": 1, "POST_TITLE": "Post N.1", "POST_DESCRIPTION" ...

Incorporate jQuery Tabs into every individual function for enhanced functionality

Is it possible to have multiple tab functions on the same page using a script for creating tabs easily? I've tried using an each.function to wrap the tabs, but I haven't been successful. The tab changes simultaneously on all rows. For reference, ...

Display JSON data in a dynamic d3.js visualization

Using d3.js, I have created a chart that displays weekly scores when hovering over the months. To view the chart, click here: https://jsfiddle.net/qp7L1hob/1/ In my database, I maintain a table called Table pointsScored where I keep records of employee s ...