我认为您应该使用一个对象按国家/地区对制造商进行分组。像这样:
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);
演示
如果您仍然想获得您所描述的结果,那么您可以使用这样的解决方案:
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);
演示