我有一个阵列,其中包含来自多家公司的注册人(一些来自同一家公司,有些不是),我需要计算同一家公司的注册人数。所以我需要一个数字告诉我有多少人(在第一个之后)来自独特的公司注册。
说我有一个数组:
var company_names = ['acme', 'acme', 'bobo', 'comanche', 'acme', 'comanche'];
和变量:
var companies_eligible_for_discount = 0;
我如何计算分配3个折扣? (2表示“极致”,1表示“科曼奇”)
答案 0 :(得分:5)
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;
}
答案 1 :(得分:0)
我提供了一个代码片段,您可以在控制台中运行以测试功能,并创建了一个可以立即使用的演示函数(删除console.log语句)。它返回一组公司名称。
实际上,我正在使用的事实是Javascript具有对象的本机关联数组,因此我将toLowerCase
字段名(在您的情况下为公司)指定为关联数组查找点的字段。如果fieldname不是属性,那么这是我们第一次添加它。在我们第一次添加一个(考虑“bobo”)时,我们将其设置为零。在随后的时间里,我们将它增加一个。
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 );