gpt4 book ai didi

javascript - 数据未正确分组

转载 作者:行者123 更新时间:2023-11-29 18:20:35 25 4
gpt4 key购买 nike

我有包含国家名称的源数组和包含产品的其他数组。两个数组的索引相等。

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;
}

最佳答案

我认为您应该使用一个对象来按国家/地区对制造商进行分组。像这样:

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

关于javascript - 数据未正确分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19130759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com