我有这种形式的数组
['203,448', '204,297', '204,448', '205,297', '230,448', '231,297', '24,448', '24,297','203,548', '204,548', '204,548' ]欲望输出:
0:['203,448', '204,448', '230,448','24,448', ]
1: [ '204,297', '205,297', '231,297', '24,297']
2: ['203,548', '204,548', '204,548']我想在两个特性的基础上分离元素,即203,448和204,297。
发布于 2017-10-13 08:01:52
您可以为字符串的同一第二部分接受哈希表,并在数组中收集相同的项。
var data = ['203,448', '204,297', '204,448', '205,297', '230,448', '231,297', '24,448', '24,297', '203,548', '204,548', '204,548'],
hash = Object.create(null),
result = data.reduce(function (r, a) {
var key = a.split(',')[1];
if (!hash[key]) {
hash[key] = [];
r.push(hash[key]);
}
hash[key].push(a);
return r;
}, []);
console.log(result);.as-console-wrapper { max-height: 100% !important; top: 0; }
对于只放置第一部分,可以使用拆分数组。
var data = ['203,448', '204,297', '204,448', '205,297', '230,448', '231,297', '24,448', '24,297', '203,548', '204,548', '204,548'],
hash = Object.create(null),
result = data.reduce(function (r, a) {
var s = a.split(',');
if (!hash[s[1]]) {
hash[s[1]] = [];
r.push(hash[s[1]]);
}
hash[s[1]].push(s[0]);
return r;
}, []);
console.log(result);.as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/46725135
复制相似问题