How to make an array of two duplicate array values ​​only in Javascript?

I have an array with registrars from several companies (some of the same companies, and some not), and I need to calculate how many people from one company have registered. Therefore, I need a number that tells me how many additional people (after the first) from unique companies have registered.

Let's say I have an array:

var company_names = ['acme', 'acme', 'bobo', 'comanche', 'acme', 'comanche']; 

and variable:

 var companies_eligible_for_discount = 0; 

How can I consider that 3 discounts should be assigned? (2 for "acme" and 1 for "comanche")

+4
source share
2 answers
 var dupes = {}; company_names.forEach(function(v,i) { if( v in dupes ) { dupes[v]++; companies_eligible_for_discount++; } else dupes[v] = 0; }); 

 var dupes = {}, v, i; for( i = 0; i < company_names.length; ++i ) { v = company_names[i]; if( v in dupes ) { dupes[v]++; companies_eligible_for_discount++; } else dupes[v] = 0; } 
+5
source

I provided a snippet that you can run in the console to test the functionality, and created a demo function that you could use right away (deleting console.log statements). It returns an array of company names.

In fact, what I'm doing is using the fact that Javascript has its own associative arrays for objects, so I assign the name toLowerCase field (in your case the company) as the field for the search point of the associative array. If the field name is no longer a property, then this is the first time we have added it. The first time we add one (consider "bobo"), we will set it to zero. In subsequent times, we increase it by one.

 function getCompaniesOver(companyArray, discountMinimum){ var tallyObject = {}, retArray = [], has = Object.prototype.hasOwnProperty; //I'm making sure that we have a clean reference to the hasOwnProperty for(var k in companyArray){ var s = companyArray[k]+''; s = s.toLowerCase(); if (has.call(tallyObject,s)){ tallyObject[s]++; } else { tallyObject[s] = 0; } } console.log(tallyObject); // for debugging insepection. console.log('companies with ' +companies_eligible_for_discount+ ' number of employees above 1 attending') console.log('--------') for (var k in tallyObject){ if (tallyObject[k] >= companies_eligible_for_discount){ console.log(k); retArray.push(k); } } console.log('--------') return retArray; } var company_names_long = ['acme', 'acme', 'bobo', 'comanche', 'acme', 'comanche', 'comanche', 'acme', 'sanford & sons', 'Sanford & Sons', 'Johnson&Johnson', 'johnson&johnson']; var company_names = ['acme', 'acme', 'bobo', 'comanche', 'acme', 'comanche'], companies_eligible_for_discount = 2; //this is the range you can supply getCompaniesOver(company_names, companies_eligible_for_discount ); companies_eligible_for_discount = 1; getCompaniesOver(company_names_long, companies_eligible_for_discount ); 
0
source

Source: https://habr.com/ru/post/1383154/


All Articles