🤪Sort array of objects by string property value (ok)

https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value

index.html

<!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>
	<script type="text/javascript">
		const points = [40, 100, 1, 5, 25, 10];
		points.sort(function(a, b){
			return a - b
		});
		console.log(points);
	</script>
	<script type="text/javascript">
		var objs = [ 
	    { 
	    	first_nom: 'Lazslo', 
	    	last_nom: 'Jamf'     
	  	},
	    { 
	    	first_nom: 'Pig',    
	    	last_nom: 'Bodine'   
	    },
	    { 
	    	first_nom: 'Pirate', 
	    	last_nom: 'Prentice' 
	   	}
		];
		function compare( a, b ) {
		  if ( a.last_nom < b.last_nom ){
		    return -1;
		  }
		  if ( a.last_nom > b.last_nom ){
		    return 1;
		  }
		  return 0;
		}
		objs.sort( compare );
		console.log(objs);
	</script>
</body>
</html>

Result 1

[
    1,
    5,
    10,
    25,
    40,
    100
]

Result 2

[
    {
        "first_nom": "Pig",
        "last_nom": "Bodine"
    },
    {
        "first_nom": "Lazslo",
        "last_nom": "Jamf"
    },
    {
        "first_nom": "Pirate",
        "last_nom": "Prentice"
    }
]

Last updated