-1

I have some data in an array. I want to groupby the data based on a specific column. Please note, its not sorting that I want.

Example:

Name    Dept
AAA         D1
BBB         D2
CCC         D1
DDD         D2
EEE         D1
FFF         D2

I want to groupby the data based on dept. SO the output should be as below:

Name Dept
AAA  D1
CCC  D1
EEE  D1
BBB  D2
DDD  D2
FFF  D2

I want to implement this using jQuery\Javascript. This is to populate a grid with data, and there are around 8 columns, though I have just shown two columns in the above example. The idea here is to groupby a specific column, say Dept .

Please suggest.

Thanks in advance!!!

1

1 Answer 1

0

Should be something like this:

var objects = [
    {Name: "AAA", Dept: "D1"},
    {Name: "BBB", Dept: "D2"},
    {Name: "CCC", Dept: "D1"},
    {Name: "DDD", Dept: "D2"},
    {Name: "EEE", Dept: "D1"},
    {Name: "FFF", Dept: "D2"}
];

var sorted = {};
for(var k in objects){
    var obj = objects[k];

    // Create new Group key if not exist
    if(!sorted[obj.Dept])
        sorted[obj.Dept] = [];

    sorted[obj.Dept].push(obj);
}

console.log(sorted);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your response. I understand this is sorting. But I want to groupby. Because my real data may not contain D1 or D2. We cannot use > operator. Not sure if am correct !
So you asked it wrongly. You want that ALL 'Dept' stay in the same key?
Ya, Thats what I have shown in the example. May be i did not convey my message properly...
If it's not like that, it must be like this. Your question is not clear

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.