Mohammad Ahmad Shabbir
Mohammad Ahmad Shabbir

Reputation: 143

How to dynamically create an array using JavaScript?

i have array in this form

['203,448', '204,297', '204,448', '205,297', '230,448', '231,297', '24,448', '24,297','203,548', '204,548', '204,548' ]

Desire Output :

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

I want to sepreate Elements on the base of 2 featur i.e 203,448 and 204 ,297

Upvotes: 0

Views: 52

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386883

You could take a hash table for same second part of the string and collect same items in an array.

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

For putting only the first part, you could use splitting array

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

Upvotes: 1

Related Questions