Skip to content

Instantly share code, notes, and snippets.

@tranchausky
Created January 13, 2021 08:23
Show Gist options
  • Select an option

  • Save tranchausky/0c7ef81f9c55a21b3f43858440ffc627 to your computer and use it in GitHub Desktop.

Select an option

Save tranchausky/0c7ef81f9c55a21b3f43858440ffc627 to your computer and use it in GitHub Desktop.
<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