Created
January 13, 2021 08:23
-
-
Save tranchausky/0c7ef81f9c55a21b3f43858440ffc627 to your computer and use it in GitHub Desktop.
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
| <script> | |
| function sortObj(list, key) { | |
| function compare(a, b) { | |
| a = a[key]; | |
| b = b[key]; | |
| var type = (typeof(a) === 'string' || | |
| typeof(b) === 'string') ? 'string' : 'number'; | |
| var result; | |
| if (type === 'string') result = a.localeCompare(b); | |
| else result = a - b; | |
| return result; | |
| } | |
| return list.sort(compare); | |
| } | |
| var cars= [{brand: 'audi', speed: 240}, {brand: 'fiat', speed: 190}]; | |
| //var carsSortedByBrand = sortObj(cars, 'brand'); | |
| var carsSortedBySpeed = sortObj(cars, 'speed'); | |
| console.log(cars) | |
| var mobile= {}; | |
| mobile[0]={brand: 'audi', speed: 240} | |
| mobile[1]={brand: 'fiat', speed: 190} | |
| var mobileBySpeed = sortObj(cars, 'speed'); | |
| console.log(mobileBySpeed) | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment