Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a multidimensional javascript array that's filled with a lot of redundant data that I'd like grouped together by elements within itself...

// current array
pGroup = ([pm, name]); // [0][0] = pm0, [0][1] = name0 ... [n][0] = pmn, [n][1] = namen

My goal is to filter out all of the redundant pm's, then group the names into an array attached to their respective names.

I've tried several failed combinations of $.grep, $.filter, and have tinkered with underscore.js a bit to find a solution.. but as of yet I've come up empty.

Any guidance to a solution would be greatly appreciated.

EDIT:

// Current array

pGroup [

    [0]
    0: "Whimpenny, Walter"
    1: "105495-005_SMS M&S Option Year 1"
    ,

    [1]
    0: "Whimpenny, Walter"
    1: "105495-005_SMS M&S Option Year 2"
    , 

    [2]
    0: "Sukumar, Prasanna"
    1: "DISA-JCSS/Staff Aug-SO #203868" 

]

// requested result

pGroup [

    [0] 0: "Whimpenny, Walter" 1: ["105495-005_SMS M&S Option Year 1", "105495-005_SMS M&S Option Year 2"]

    [1] 0: "Sukumar, Prasanna" 1: ["DISA-JCSS/Staff Aug-SO #203868" ]

]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
158 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use an object keyed off the names to group the values.

var result_obj = {};
$.each(pGroup, function(i, e) {
    var name = e[0], val = e[1];
    if (result_obj[name]) {
        result_obj[name].push(val);
    } else {
        result_obj[name] = [val];
});

Then collect them back into an array.

pGroup = [];
$.each(result_obj, function(i, e) {
    pGroup.push([i, e]);
});

However, I suggest that you not use a multidimensional array for the results. Arrays should be used for uniform, ordered collections. Your second dimension is not uniform, it should be an object like this:

$.each(result_obj, function(i, e) {
    pGroup.push({name: i, values: e});
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...