Skip to content

Instantly share code, notes, and snippets.

@umidjons
Last active January 16, 2024 13:00
Show Gist options
  • Star 67 You must be signed in to star a gist
  • Fork 22 You must be signed in to fork a gist
  • Save umidjons/9614157 to your computer and use it in GitHub Desktop.
Save umidjons/9614157 to your computer and use it in GitHub Desktop.
JavaScript: sort object properties by value (numeric or string)

Sort object properties by value (values are text)

I have following object:

var cities={10:'Tashkent', 14:'Karakalpakiya', 16:'Andijan'};

I want sort it by city names, so after sort it should be:

var cities={16:'Andijan', 14:'Karakalpakiya', 10:'Tashkent'};

But I can't sort object properties, instead can convert object into array, then sort items.

function sortProperties(obj)
{
  // convert object into array
	var sortable=[];
	for(var key in obj)
		if(obj.hasOwnProperty(key))
			sortable.push([key, obj[key]]); // each item is an array in format [key, value]
	
	// sort items by value
	sortable.sort(function(a, b)
	{
		var x=a[1].toLowerCase(),
			y=b[1].toLowerCase();
		return x<y ? -1 : x>y ? 1 : 0;
	});
	return sortable; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
}

Example:

var sortedCities=sortProperties(cities);
console.log(sortedCities); // [[16, 'Andijan'], [14, 'Karakalpakiya'], [10, 'Tashkent']]

Sort object properties by value (values are numbers)

I have following object:

var cities={Tashkent:447, Karakalpakiya:900, Andijan:120};

I want sort it by city rating, so after sort it should be:

var cities={Andijan:120, Tashkent:447, Karakalpakiya:900};

But again I can't sort object properties, instead can convert object into array, then sort items.

function sortProperties(obj)
{
  // convert object into array
	var sortable=[];
	for(var key in obj)
		if(obj.hasOwnProperty(key))
			sortable.push([key, obj[key]]); // each item is an array in format [key, value]
	
	// sort items by value
	sortable.sort(function(a, b)
	{
	  return a[1]-b[1]; // compare numbers
	});
	return sortable; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
}

Example:

var sortedCities=sortProperties(cities);
console.log(sortedCities); // [[Andijan, 120], [Tashkent, 447], [Karakalpakiya, 900]]

###Improved version with additional parameter to set sort type (numeric or text)

/**
 * Sort object properties (only own properties will be sorted).
 * @param {object} obj object to sort properties
 * @param {bool} isNumericSort true - sort object properties as numeric value, false - sort as string value.
 * @returns {Array} array of items in [[key,value],[key,value],...] format.
 */
function sortProperties(obj, isNumericSort)
{
	isNumericSort=isNumericSort || false; // by default text sort
	var sortable=[];
	for(var key in obj)
		if(obj.hasOwnProperty(key))
			sortable.push([key, obj[key]]);
	if(isNumericSort)
		sortable.sort(function(a, b)
		{
			return a[1]-b[1];
		});
	else
		sortable.sort(function(a, b)
		{
			var x=a[1].toLowerCase(),
				y=b[1].toLowerCase();
			return x<y ? -1 : x>y ? 1 : 0;
		});
	return sortable; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
}
@0zkr1
Copy link

0zkr1 commented Oct 4, 2019

@ForgeableSum: You can also do:
newObject = sortedArray.reduce( (obj, ent) => { obj[ ent[0] ] = ent[1]; return obj; }, /** @type {Any} */({}) );

@kl3sk
Copy link

kl3sk commented Oct 28, 2019

@sudhir600 this is because chrome/firefox console re sort them naturally. Use JSON.stringify and see that is sorted as you wish

@andres-paris
Copy link

Thanks a lot! It works perfectly for me.

@macyhvt
Copy link

macyhvt commented Jan 16, 2024

Saw this from one of colleagues comment and thanks for the great help. Cheers !!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment