JSFiddle - React, Tailwind, and code Playground

Dynamic sorting by multiple fields

by Nalin Sajwan

HTML

<pre id="finalOutput">
</pre>

JavaScript

var unsortedArr = [
	{
		'name': 'Nalin',
		'class': '12',
		'section': 'A'
	},
	{
		'name': 'Arvind',
		'class': '12',
		'section': 'B'
	},
	{
		'name': 'Kamal',
		'class': '10',
		'section': 'A'
	},
	{
		'name': 'Ajay',
		'class': '10',
		'section': 'A'
	},
	{
		'name': 'Aman',
		'class': '10',
		'section': 'B'
	},
	{
		'name': 'Anshul',
		'class': '12',
		'section': 'A'
	}
];

function dynamicSort(property) {
	return function (obj1, obj2) {
		return obj1[property] > obj2[property] ? 1 
			: obj1[property] < obj2[property] ? - 1 : 0;
	}
};

function dynamicSortMultiple() {
	/*
	 * save the arguments object as it will be overwritten
	 * note that arguments object is an array-like object
	 * consisting of the names of the properties to sort by
	 */
	var props = arguments;

	return function (obj1, obj2) {
		var i = 0,
		result = 0,
		numberOfProperties = props.length;
		/* try getting a different result from 0 (equal)
		 * as long as we have extra properties to compare
		 */
		while (result === 0 && i < numberOfProperties) {
			result = dynamicSort(props[i]) (obj1, obj2);
			i++;
		}

		return result;
	}
};

var sortedArr = unsortedArr.sort(dynamicSortMultiple('class', 'section', 'name'));

document.getElementById("finalOutput").innerHTML = JSON.stringify(sortedArr, null, 4);

console.log('Sorted Array ==> ', JSON.stringify(sortedArr, null, 4));