Last active
August 15, 2022 14:05
-
-
Save PetiDev/c5ce84fc5269bb1bda32c4cbce9391f5 to your computer and use it in GitHub Desktop.
Sort JSON by value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* Uses bubble sort to sort JSON Objects by value, | |
* useing the condition defined in the callback | |
* | |
* @category Object | |
* @param {Function} callback sorting condition | |
* @returns {Object} Returns the sorted Object | |
* | |
* | |
* @example | |
* let testJson = { | |
* "a":2, | |
* "b":9, | |
* "c":3, | |
* "d":1, | |
* } | |
* testJson.sort((a,b) => a > b) | |
* //{ d: 1, a: 2, c: 3, b: 9 } | |
*/ | |
Object.prototype.sort = function bubbleSort(callback) { | |
const obj = this | |
let keys = Object.keys(obj) | |
let values = Object.values(obj) | |
let len = values.length; | |
let checked; | |
do { | |
checked = false; | |
for (let i = 0; i < len; i++) { | |
if (callback(values[i], values[i + 1])) { | |
let tmp = values[i]; | |
values[i] = values[i + 1]; | |
values[i + 1] = tmp; | |
let tmpKeys = keys[i] | |
keys[i] = keys[i + 1]; | |
keys[i + 1] = tmpKeys; | |
checked = true; | |
} | |
} | |
} while (checked); | |
let newObj = {} | |
for (let i = 0; i < keys.length; i++) { | |
newObj[keys[i]]=values[i] | |
} | |
return newObj; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment