Sorting array in ascending and descending order on object data

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<body>
	<button type="button" onclick="doSort();">Sort</button>
	<button type="button" onclick="doReverse();">Reverse</button>

	<script type="text/javascript">
		"use strict"
		let users=[
		{
			fname:'aman',
			age:20
		},
		{
			fname:'ajay',
			age:19
		},
		{
			fname:'rakesh',
			age:18
		},
		{
			fname:'Lalit',
			age: 25
		},
		{
			fname:'Pradeep',
			age: 22
		},
		{
			fname:'Kiran',
			age:22
		}
	];


	function compare(objectA, objectB){		
		let x=0;
		if(objectA.age > objectB.age){
			x=1;
		}
		else if(objectA.age < objectB.age){
			x=-1;
		}		
		return x;		
	}

	function doSort(){
		users.sort(compare)
		console.log(users);
	}

	function doReverse(){
		users.reverse();
		console.log(users);	
	}
	
	</script>	
</body>
</html>
© 2016 - 2022, All Rights are Reserved.