我認爲你應該按國家使用對象組製造商。就像這樣:
var conutries,
manufacturers,
i,
len,
country,
manufacturerByCountry;
countries = ['China', 'China', 'Korea', 'USA', 'USA'];
manufacturers = ['Lenovo', 'Asus', 'Samsung', 'Apple', 'Blackberry'];
len = countries.length;
manufacturerByCountry = {};
// expected result:
// array : {'China': ['Lenovo', 'Asus'], 'Korea': ['Samsung'] ... }
for(i = 0; i < len; i++) {
country = countries[i];
if(!manufacturerByCountry[country]) {
manufacturerByCountry[country] = [];
}
manufacturerByCountry[country].push(manufacturers[i]);
}
console.log(manufacturerByCountry);
DEMO
如果您仍然希望得到您的問題所描述的結果,那麼你可以通過這樣的一種解決方案:
var conutries,
manufacturers,
i,
len,
country,
manufacturerByCountry,
countryIndex,
index;
countries = ['China', 'China', 'Korea', 'USA', 'USA'];
manufacturers = ['Lenovo', 'Asus', 'Samsung', 'Apple', 'Blackberry'];
len = countries.length,
manufacturerByCountry = [],
countryIndex = {};
// expected result:
// array : [[China, [Lenovo, Asus]], [Korea, [Samsung]] ... ]
for(i = 0; i < len; i++) {
country = countries[i];
if(countryIndex[country] === undefined) {
index = manufacturerByCountry.push([country, []]) - 1;
countryIndex[country] = index;
} else {
index = countryIndex[country];
}
manufacturerByCountry[index][1].push(manufacturers[i]);
}
console.log(manufacturerByCountry);
DEMO
有爲什麼要使用2個陣列,而不是一個JSON對象中的任何特別的原因? – jeff
如果美國那麼陣列應該是:USA {Apple,Blackberry} right –
真的想要:'[{中國:[聯想,華碩]},{韓國:[三星]} ...''? – RobG