728x90
This was a small issue I came across recently and the solution I found was so brilliant I thought it was worth sharing on here.
So the problem was that I had an array like this:
var obj = [
{
"one": 1,
"two": 9
}, {
"one": 3,
"two": 5
}, {
"one": 1,
"two": 2
}
];
and I wanted to sort it by "one" and then by "two" to get a result like this:
var obj = [
{
"one": 1,
"two": 2,
}, {
"one": 1,
"two": 9
}, {
"one": 3,
"two": 5
}
];
sounds simple enough right? I thought so too, but the sorting algorithm that the browser is using limits your options when it comes to sorting by multiple fields. After a bit of researching I stumbled upon this wonderful solution: http://stackoverflow.com/questions/13211709/javascript-sort-array-by-multiple-number-fields
obj.sort(function(a, b) {
return a["one"] - b["one"] || a["two"] - b["two"];
});
This will sort your array by "one" and if they are the same (ie. 0) then it will sort by "two". It's simple, concise, readable, and best of all - works perfectly.
'WEB > JavaScript' 카테고리의 다른 글
delete operator (0) | 2021.08.14 |
---|---|
“javascript sort json array by multiple values” Code Answer (0) | 2021.06.21 |
[JavaScript] 자바스크립트 2차원 배열 선언 및 사용법 (0) | 2021.06.11 |
Implementing Bubble Sort in Javascript (0) | 2021.06.11 |
charAt 메서드 & charCodeAt 메서드 (0) | 2021.03.20 |