arrays - What is the best way to remove excessive duplicates from an object in Javascript? -


consider following object in javascript (this large object, have included portion of it).

enter image description here

i want apply following:

for each unique user, allow maximum of 4 random leads , remove rest.

for example, if have 10 different users, each user appearing 5 times each, there 50 records in object. want keep 4 each user (it not matter 4). leave total of 40 records.

i not sure start problem, have done far:

1) create array containing distinct list of users:

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

2) not sure next. guess need loop through object (lets call leads) , compare unique users array. if there match, counter should increased, if counter = 4 lead should skipped. pseudo code:

        (var = 0; < leads.length; i++) {       if (leads[i].user == //anything in users array//) {         //check existing count property on unique users array         // if not exist, add count property users array         // else, if count 4, destroy [leads[i]]       }//end if     }//end 

am on right track? or javascript have better way of doing this?

you can use array#reduce. create object , push lead, once length equal 4 stop pushing it.

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]);


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -