我的源数组包含国家/地区的名称和其他包含产品的数组。两个数组的指标是相等的。
array1:{China, China, Korea, USA, USA},
array2:{Lenovo, Asus, Samsung, Apple, Blackberry},
result : array : {{China, {Lenovo, Asus}}, {Korea, {Samsung}} ... }
但我无法正确分组数组。我总是得到一个结果
{{China, {Lenovo}},{China, {Asus}} ... }.
我的代码是:
for (i = 0; i < XArray.length; i++) {
var pointsArray = [];
for (j = 0; j < XArray.length; j++) {
if (XArray[i] == XArray[j]) {
pointsArray.push([parseFloat(YArray[i]), parseFloat(ZArray[i])]);
}
}
dataSource.push({
name: i,
data: pointsArray.slice()
});
pointsArray.length = 0;
}
答案 0 :(得分:4)
我认为你应该使用一个对象按国家对制造商进行分组。像这样:
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);
答案 1 :(得分:0)
对语法不太确定,但我认为您正在尝试这样做:
var array1 = ['China', 'China', 'Korea', 'USA', 'USA'];
var array2 = ['Lenovo', 'Asus', 'Samsung', 'Apple', 'Blackberry'];
var result = [];
var name, names = {};
var nameCount = 0;
var obj;
for (var i=0, iLen=array1.length; i<iLen; i++) {
name = array1[i];
// If haven't found name already, setup structure
// so value can be added after the block
if (!(name in names)) {
// Add name to the list of names and remember its index
names[name] = nameCount;
// Create a new object
obj = {};
// Give it a property with value of name and assign an array
obj[name] = [];
// Add it to results
result.push(obj);
// Increment index for next time
++nameCount;
}
// Add member of array2 to name object's array
result[names[name]][name].push(array2[i]);
}
创建一个对象数组,如:
[
{China: ['Lenovo', 'Asus']},
{Korea: ['Samsung']},
{USA: ['Apple', 'Blackberry']}
]