Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-sorting a multi-dimensional array

var availableTags = [
    {value:"fruit",desc:"fruit",groupId:2,userId:4},
    {value:"aGan",desc:"normal user",groupId:4,userId:5},
    {value:"father's home ",desc:"normal user",groupId:2,userId:4}     

  ].sort(function(a, b) {  return a.groupId > b.groupId; });

This sorts by groupId field, but how do I to sort by groupId and value?

like image 617
Control Freak Avatar asked Feb 21 '12 08:02

Control Freak


People also ask

Can you sort a multidimensional array?

Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.

How do you sort a multidimensional list?

Use sorted() with a lambda function to sort a multidimensional list by column. Call sorted(iterable, key=None) with key set to a lambda function of syntax lambda x: x[i] to sort a multidimensional list iterable by the i th element in each inner list x .

What is multi multidimensional array?

A multidimensional array in MATLAB® is an array with more than two dimensions. In a matrix, the two dimensions are represented by rows and columns. Each element is defined by two subscripts, the row index and the column index.

What is multi dimension array?

A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays are stored in row-major order. The general form of declaring N-dimensional arrays is: data_type array_name[size1][size2]....[sizeN];


2 Answers

Change the return statement to

return a.groupId > b.groupId || (a.groupId == b.groupId && a.value > b.value);
like image 181
Philip Sheard Avatar answered Sep 17 '22 05:09

Philip Sheard


How about

.sort(function (a, b) {
    var firstGroupId = a.groupId;
    var secondGroupId = b.groupId;

    return (firstGroupId === secondGroupId) ? a.value > b.value : firstGroupId > secondGroupId;
});
like image 26
helpermethod Avatar answered Sep 20 '22 05:09

helpermethod