我提供,你可以在控制台上运行测试功能的片段,并创建了一个演示功能你可以立即使用(移除console.log语句)。它返回一组公司名称。
我正在做的事情是使用Javascript具有对象的本机关联数组这一事实,因此我将toLowerCase
字段名(在您的情况下是公司)指定为关联数组查找点的字段。如果字段名称不是属性,那么这是我们第一次添加它。我们第一次添加一个(考虑“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);
我一直在尝试一切。非常到了我想从广场1开始的地步。 –
让我知道我的答案是不是很容易理解。我知道我为它添加了一点肉,希望能为它保留它。 RightSaidFred给出了更紧凑的版本,它只取决于你想要开始和结束的东西。 – jcolebrand