Link to home
Start Free TrialLog in
Avatar of mainrotor
mainrotor

asked on

I need help grouping an Array in my JavaScript code

Hi Experts,
I am working on a MVC.Net application with C#.Net code-behind.

I am using an Array in one of my views.
I am able to populate my array just fine, but I need to do the following once I have populated my array:
1. Group by the following fields: order, item, description
2. Sort by the following fields: order, item, description

I have included my javascript code below.  
Please show me how to do my grouping and sorting of my javascript array.

var claimsHeader = new Array(); 



function onDataBoundHeader(arg) {
	var dataItemsHeader = arg.sender.dataSource.view();

        for (var j = 0; j < dataItemsHeader.length; j++) {
            var order = dataItemsHeader[j].get("Item");
            var item = dataItemsHeader[j].get("Market");
            var description = dataItemsHeader[j].get("Description");
            
            var claims = new Array(order, item, description);
            claimsHeader.push(claims);
        }
}

Open in new window


Thank you in advance,
mrotor
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

When you say " Group by the following fields: order, item, description" how do you mean group - can you explain a bit more.

For sorting just use the Array.sort method.

claimsHeader.sort(function(a, b) {
   if (a.order < b.order) return -1;
   if (a.order > b.order) return 1;
   if (a.item < b.item) return -1;
   if (a.item > b.item) return 1;
   if (a.description < b.description) return -1; // You may need to use strtolower if you don't want case to be a factor
   if (a.description > b.description) return 1;
   return 0;
});

Open in new window

Avatar of mainrotor
mainrotor

ASKER

The array I create, is generated from a grid.  The data that loads into my array is sometimes repeated.
For example:

ORDER     ITEM          DESCRIPTION
ABC          SHIRT         SILK SHIRT
ABC          SHIRT         SILK SHIRT
DEF           PANTS       POLYESTER PANTS

I want the array to group by ORDER, ITEM, and DESCRIPTION so that the results are grouped as follows:
ABC          SHIRT         SILK SHIRT
DEF           PANTS       POLYESTER PANTS



How can I do this?
Do you mean you want to an array unique 'records' and then sort?
Yes, Norie.  I want an array's unique records and then sort.

Thank you for helping me clarify what it is I need.  :-)

How can I accomplish this?
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Julian,
I will try your suggestion and report my results.

mrotor
Thanks Julian.
Your suggestion worked.
You are welcome.