How to sort an array of objects by multiple fields?
You could use a chained sorting approach by taking the delta of values until it reaches a value not equal to zero.
var data = [{ h_id: "3", city: "Dallas", state: "TX", zip: "75201", price: "162500" }, { h_id: "4", city: "Bevery Hills", state: "CA", zip: "90210", price: "319250" }, { h_id: "6", city: "Dallas", state: "TX", zip: "75000", price: "556699" }, { h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500" }];
data.sort(function (a, b) { return a.city.localeCompare(b.city) || b.price - a.price;});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
How do you sort an array on multiple columns?
If owner names differ, sort by them. Otherwise, use publication name for tiebreaker.
function mysortfunction(a, b) {
var o1 = a[3].toLowerCase();
var o2 = b[3].toLowerCase();
var p1 = a[1].toLowerCase();
var p2 = b[1].toLowerCase();
if (o1 < o2) return -1;
if (o1 > o2) return 1;
if (p1 < p2) return -1;
if (p1 > p2) return 1;
return 0;
}
How does one sort a multi dimensional array by multiple columns in JavaScript?
The array literal []
is preferred over new Array
. The notation {0,4,3,1}
is not valid and should be [0,4,3,1]
.
Is there a need for reinventing the wheel? Two arrays can be joined using:
originalArray = originalArray.concat(addArray);
Elements can be appended to the end using:
array.push(element);
Arrays have a method for sorting the array. By default, it's sorted numerically:
// sort elements numerically
var array = [1, 3, 2];
array.sort(); // array becomes [1, 2, 3]
Arrays can be reversed as well. Continuing the previous example:
array = array.reverse(); //yields [3, 2, 1]
To provide custom sorting, you can pass the optional function argument to array.sort()
:
array = [];
array[0] = [1, "first element"];
array[1] = [3, "second element"];
array[2] = [2, "third element"];
array.sort(function (element_a, element_b) {
return element_a[0] - element_b[0];
});
/** array becomes (in order):
* [1, "first element"]
* [2, "third element"]
* [3, "second element"]
*/
Elements will retain their position if the element equals an other element. Using this, you can combine multiple sorting algoritms. You must apply your sorting preferences in reverse order since the last sort has priority over previous ones. To sort the below array by the first column (descending order) and then the second column (ascending order):
array = [];
array.push([1, 2, 4]);
array.push([1, 3, 3]);
array.push([2, 1, 3]);
array.push([1, 2, 3]);
// sort on second column
array.sort(function (element_a, element_b) {
return element_a[1] - element_b[1];
});
// sort on first column, reverse sort
array.sort(function (element_a, element_b) {
return element_b[0] - element_a[0];
});
/** result (note, 3rd column is not sorted, so the order of row 2+3 is preserved)
* [2, 1, 3]
* [1, 2, 4] (row 2)
* [1, 2, 3] (row 3)
* [1, 3, 3]
*/
To sort latin strings (i.e. English, German, Dutch), use String.localeCompare
:
array.sort(function (element_a, element_b) {
return element_a.localeCompare(element_b);
});
To sort date's from the Date
object, use their milliseconds representation:
array.sort(function (element_a, element_b) {
return element_a.getTime() - element_b.getTime();
});
You could apply this sort function to all kind of data, just follow the rules:
x
is the result from comparing two values which should be returned by a function passed to array.sort
.
x < 0
:element_a
should come beforeelement_b
x = 0
:element_a
andelement_b
are equal, the elements are not swappedx > 0
:element_a
should come afterelement_b
Sort multidimensional array by multiple columns
You need array_multisort
$mylist = array(
array('ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting'),
array('ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting'),
array('ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party'),
array('ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party')
);
# get a list of sort columns and their data to pass to array_multisort
$sort = array();
foreach($mylist as $k=>$v) {
$sort['title'][$k] = $v['title'];
$sort['event_type'][$k] = $v['event_type'];
}
# sort by event_type desc and then title asc
array_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$mylist);
As of PHP 5.5.0:
array_multisort(array_column($mylist, 'event_type'), SORT_DESC,
array_column($mylist, 'title'), SORT_ASC,
$mylist);
$mylist
is now:
array (
0 =>
array (
'ID' => 4,
'title' => 'Duct Tape Party',
'event_type' => 'party',
),
1 =>
array (
'ID' => 3,
'title' => 'Mario Party',
'event_type' => 'party',
),
2 =>
array (
'ID' => 1,
'title' => 'Boring Meeting',
'event_type' => 'meeting',
),
3 =>
array (
'ID' => 2,
'title' => 'Find My Stapler',
'event_type' => 'meeting',
),
)
Sort an array of associative arrays by multiple columns using a combination of ascending, descending, regular, numeric, and natural sorting
I think you have to implement a custom comparison function for this behavior:
function myCmp($a, $b) {
$nameCmp = strnatcasecmp($a['Name'], $b['Name']);
$ageCmp = strnatcasecmp($a['Age'], $b['Age']);
$codeCmp = strnatcasecmp($a['Code'], $b['Code']);
if ($nameCmp != 0) // Names are not equal
return($nameCmp);
// Names are equal, let's compare age
if ($ageCmp != 0) // Age is not equal
return($ageCmp * -1); // Invert it since you want DESC
// Ages are equal, we don't need to compare code, just return the comparison result
return($codeCmp);
}
Then you can call usort($array, 'myCmp');
and should get the desired sorting
How to sort multiple columns data in Multi-Dimensional array?
I also face the same issue and found a good solution for sort multiple columns data in Multi-Dimensional array.
Check the below code
(function() { function deepsort(){ var i, order= arguments, L= order.length, tem; return a.sort(function(a, b){ i= 0; while(i < L){ tem= order[i++]; var res = tem.split("_"); var ao= a[res[0]] || 0, bo= b[res[0]] || 0; if(ao== bo) continue; if(res[1] == "ASC"){ return ao > bo? 1: -1; } if(res[1] == "DESC"){ return ao < bo? 1: -1; } } return 0; });}
var a= [ ["2015-08-09", 1.2, 1.20, 2.1], ["2015-08-10", 1.2, 1.21, 2.11], ["2015-08-11", 1.2, 0.99, 2.20], ["2015-10-29", 1.2, 1.12, 2.22], ["2015-09-10", 1.21, 1.19, 2.00]];document.write(deepsort(1+"_ASC",2+"_ASC"));// for better result view check console logconsole.log(deepsort(1+"_ASC",2+"_ASC"))//console.log(a.deepsort(1)) })();
Sort an array with multiple columns and multiple keys in VBA
I solved it, if anyone needs it in the future, here is the code:
Public Function SortArr2DM(Arr2D As Variant, aColArr As Variant, IsAscendingArr As Variant) As Variant
Dim I As Long
Dim J As Long
Dim C As Long
Dim X As Byte
'
Dim aCol As Long
Dim TmpValue As Variant
Dim tmpArr As Variant
Dim IsSwitch As Boolean
Dim IsAscending As Boolean
tmpArr = Arr2D
For I = LBound(tmpArr) To UBound(tmpArr)
For J = I + 1 To UBound(tmpArr)
For X = 0 To UBound(aColArr)
aCol = aColArr(X)
IsAscending = IsAscendingArr(X)
If IsAscending Then
If tmpArr(I, aCol) > tmpArr(J, aCol) Then
IsSwitch = True
Exit For
ElseIf tmpArr(I, aCol) < tmpArr(J, aCol) Then
IsSwitch = False
Exit For
End If
Else
If tmpArr(I, aCol) < tmpArr(J, aCol) Then
IsSwitch = True
Exit For
ElseIf tmpArr(I, aCol) > tmpArr(J, aCol) Then
IsSwitch = False
Exit For
End If
End If
Next
If IsSwitch Then
For C = LBound(tmpArr, 2) To UBound(tmpArr, 2)
TmpValue = tmpArr(I, C)
tmpArr(I, C) = tmpArr(J, C)
tmpArr(J, C) = TmpValue
Next
IsSwitch = False
End If
Next
Next
SortArr2DM = tmpArr
End Function
JavaScript sort array by multiple (number) fields
You should design your sorting function accordingly:
items.sort(function(a, b) {
return a.sort1 - b.sort1 || a.sort2 - b.sort2;
});
(because ||
operator has lower precedence than -
one, it's not necessary to use parenthesis here).
The logic is simple: if a.sort1 - b.sort1
expression evaluates to 0 (so these properties are equal), it will proceed with evaluating ||
expression - and return the result of a.sort2 - b.sort2
.
As a sidenote, your items
is actually a string literal, you have to JSON.parse
to get an array:
const itemsStr = `[{ "sort1": 1, "sort2": 3, "name": "a" }, { "sort1": 1, "sort2": 2, "name": "b" }, { "sort1": 2, "sort2": 1, "name": "c" }]`;const items = JSON.parse(itemsStr);items.sort((a, b) => a.sort1 - b.sort1 || a.sort2 - b.sort2);console.log(items);
Sort numpy 2d array by multiple columns
Numpy includes a native function for sub-sorting by columns, lexsort
:
idx = np.lexsort((arr[:,0], arr[:,1]))
arr_sorted = arr[idx]
Alternatively, you can use pandas syntax if you're more familiar; this will have some memory/time overhead but should be small for < 1m rows:
arr = [
[5, 0],
[3, 1],
[7, 0],
[2, 1]
]
df = pd.DataFrame(data=arr).sort_values([1,0])
arr_sorted = df.to_numpy()
output (both):
array([[5, 0],
[7, 0],
[2, 1],
[3, 1]])
Related Topics
What's the Significant Use of Unary Plus and Minus Operators
How to Fire and Forget a Promise in Nodejs (Es7)
How to Use Namespaces with Typescript External Modules
How to Display Length of Filtered Ng-Repeat Data
Pass Props to Parent Component in React.Js
Why Was the Arguments.Callee.Caller Property Deprecated in JavaScript
Difference Between Settimeout with and Without Quotes and Parentheses
Allow Google Chrome to Use Xmlhttprequest to Load a Url from a Local File
How to Check If a Checkbox Is Checked
How to Access Iframe Elements with JavaScript
Prevent Execution of Parent Event Handler
Sort Array by Firstname (Alphabetically) in JavaScript
Insert HTML at Caret in a Contenteditable Div
Angularjs "Controller As" Syntax - Clarification
In JavaScript, Why Is "0" Equal to False, But When Tested by 'If' It Is Not False by Itself