How can one effectively eliminate redundant duplicates from an object in Javascript?

Review the JavaScript object provided below (note that only a portion of the object is shown).

https://i.sstatic.net/5H0gn.png

Here is the requirement:

For each distinct user, limit the number of random leads to a maximum of 4 and discard the rest.

For instance, if there are 10 unique users, each appearing 5 times, the object will contain 50 records. The goal is to retain only 4 records for each user, resulting in a total of 40 records.

If you're unsure how to approach this problem, below are the initial steps I have taken:

1) Form an array comprising a list of unique users:

["1116", "1075", "1124"]

2) The next steps are unclear. It seems a logical approach would be to iterate through the object (referred to as 'leads') and compare it with the unique users array. If there's a match, increment a counter. Once the counter reaches 4, the lead should be excluded. Here is a draft of the pseudo code:

        for (var i = 0; i < leads.length; i++) {
      if (leads[i].user == //anything in the users array//) {
        // Check for an existing count property on the unique users array
        // If it doesn't exist, add a count property to the users array
        // Otherwise, if the count is already 4, remove [leads[i]]
      }//end if
    }//end for

Does this approach seem appropriate, or is there a more efficient method in JavaScript to achieve this?

Answer №1

Utilizing the array#reduce method can simplify this task. Simply create an object to store the leads, and once the length reaches 4, stop adding new items.

var leads = [{lead_id: 2433867, user : '1116'}, {lead_id: 2433868, user : '1116'}, {lead_id: 2433869, user : '1116'}, {lead_id: 2433870, user : '1116'}, {lead_id: 2433871, user : '1116'}, {lead_id: 2433872, user : '1116'}, {lead_id: 2433873, user : '1116'}, {lead_id: 2433874, user : '1116'}];

var result = leads.reduce((res, lead) => {
  res[lead.user] = res[lead.user] || [];
  if(res[lead.user].length < 4)
    res[lead.user].push(lead); 
  return res;
},{})

console.log(Object.values(result)[0]);

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

utilizing the JavaScript SDK to send alerts to a user's friends on Facebook

I am attempting to send a notification to a user's friend using the JS SDK on a Facebook canvas app, but I'm encountering this error in the console: POST https://graph.facebook.com/16542203957691/notifications? 400 (OK) jquery.min.js:140 c.exten ...

There was an error message saying "Unable to locate property 'getElementById' in undefined"

I am facing an issue with a jQuery filter function, and the error message it's showing is: Cannot read property 'getElementById' of undefined function CheckFilter() { var input, filter, table, tr, td, i, searchFilter; input = ...

What methods do you use to gather user inputs and transmit them to a server?

I've been struggling to find information online about how to capture user input and submit the data through a POST request to a server, even though this may have already been answered. Currently, I am working with Material UI, React, and JavaScript t ...

Is there a built-in method in Next.js 13 to secure routes from unauthorized access?

In my project, I have the following pages: /about, /user, and /user/[id]. Unfortunately, I am unable to access req.page, which provides the slug (i.e. /user/[id]), making it difficult for me to implement logic to redirect requests from unauthenticated user ...

Utilizing webpack 4's JSON tree-shaking functionality for keys that include the hyphen character

I need assistance with utilizing webpack 4's JSON tree-shaking feature as I am encountering a hurdle. Here is an example of some functional code: import { accessibility_16 } from '@collab-ui/icons/data/iconsData.json'; console.log("access ...

Dealing with numerous promises simultaneously using AngularJS Factory

I have created a code that makes multiple $http calls recursively and saves all the promises it returns in an array. Then, I resolve all of them and save the responses in another array. Now, my question is: How can I efficiently return this final array to ...

Scroll-triggered closing of modals in Next Js

I have integrated a Modal component into my Next.JS application, and I have implemented a functionality to close the modal when the user scrolls outside of it. However, this effect is also triggering when the user scrolls inside the modal. How can I modi ...

Having trouble retrieving data from JSON using JavaScript

Hey folks, I need some help with the following code snippet: function retrieveClientIP() { $.getJSON("http://192.168.127.2/getipclient.php?callback=?", function(json) { eval(json.ip); });} This function is used to fetch the IP address of visitors. When i ...

Issue with Angular UI-Router nested views: Content not displaying

I'm attempting to incorporate nested views for a webpage using angular ui-router. I have set up the state definitions according to various tutorials, but I am unable to display any content in the child views. Surprisingly, there are no errors showing ...

Obtain the row ID from a database by selecting checkboxes

I am facing a challenge when trying to remove a row from my MS Access database using checkboxes on my JSP page. Each row in the displayed database has a checkbox, but I am struggling to retrieve the rowId and link each checkbox with its respective row. Any ...

Allocating memory for an array within a struct

After reviewing the code for Redis, I came across the definition of a struct: typedef struct zskiplistNode { robj *obj; double score; struct zskiplistNode *backward; struct zskiplistLevel { struct zskiplistNode *forward; un ...

Disable location prompt feature when using AngularJS with Maps API

For my web application, I developed a feature that includes a map with custom markers using Angular loops: <map data-ng-model="mymap" zoom="4" center="[38.50, -95.00]" style="heigth:375px"> <div ng-repeat="item in list"> <marker pos ...

The significance of documenting and optimizing code execution

My coding practice is to always (or at least try to) add comments to my code. However, I have set up my server to delete those comments and extra white space before the final delivery. Should I omit comments from the live system's code (Javascript/php ...

Creating a Website for Compatibility with NoScript

During my journey of building a nameplate site from the ground up for myself, I have delved into the realms of learning and establishing my online presence. The highlight of my project is a sleek tabbed site that employs AJAX and anchor navigation to seaml ...

Meteor: Transmitting Session data from the client to the server

Below is the code snippet I am utilizing on the client side to establish the Session variable: Template.download.events({ 'click button': function() { var clientid=Random.id(); UserSession.set("songsearcher", clientid); ...

What could be causing the "undefined property read" error even though the data is clearly defined?

export async function getPrices() { const res = await fetch( "https://sandbox.iexapis.com/stable/crypto/BTCUSD/price?token=Tpk_1d3fd3aee0b64736880534d05a084290" ); const quote = await res.json(); return { props: { quote } }; } export de ...

Steps for removing the label associated with an input field in an HTML form

I attempted to use JQuery and JavaScript in order to modify the CSS of a label to make it greyed out, but unfortunately I have not been able to achieve this. The label is positioned next to a checkbox, and although I am able to disable the checkbox, I hav ...

Fix for fixed scrolling in the navigation bar

Having a website that receives traffic from different countries, including Portugal and other non-English speaking places, I decided to add a translation option. However, I encountered an issue with Google's translate feature which displays a banner a ...

Iterate through jQuery loop, clear styles, and iterate again

My goal is to animate the "top" position of an HTML element and then reset the style once the function has finished running before starting the loop again. I'm not an expert in this field, and I believe there must be a more efficient way to achieve t ...

Include the url of the html file in your JavaScript code

I have a piece of code that I want to include in my JavaScript instead of HTML. The code is as follows: <script async src="https://www.googletagmanager.com/gtag/js?id=ID"></script> Since all my functions are written in JavaScript, I ...