我提供,你可以在控制檯上運行測試功能的片段,並創建了一個演示功能你可以立即使用(移除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