如何使用JavaScript动态创建数组?

时间:2017-10-13 07:54:55

标签: javascript arrays dynamic

我有这种形式的数组

['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']

我想在2个特征的基础上找到元素 即203, 448 和204, 297

1 个答案:

答案 0 :(得分:1)

您可以为字符串的相同第二部分获取哈希表,并在数组中收集相同的项目。



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