Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

jquery - group data within a multidimensional javascript array

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...