Javascript Sorting

In this example below you will see how to do a Javascript Sorting with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by alaneicker, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright alaneicker ©
  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Javascript Sorting</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <h3>Unsorted</h3>
<ul id="unsorted-names"></ul>

<h3>Sorted by Age: Ascending</h3>
<ul id="sorted-by-age-asc"></ul>

<h3>Sorted by Age: Descending</h3>
<ul id="sorted-by-age-dsc"></ul>

<h3>Sorted by Name: Alphabetical</h3>
<ul id="sorted-by-name"></ul>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/alaneicker/javascript-sorting-eMLNjQ */
body {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 16px;
  line-height: 1.5;
}

/*Downloaded from https://www.codeseek.co/alaneicker/javascript-sorting-eMLNjQ */
var items = [
  { name: 'Edward', age: 21 },
  { name: 'Sheryl', age: 37 },
  { name: 'Andy', age: 45 },
  { name: 'Tes', age: 12 },
  { name: 'Mark', age: 13 },
  { name: 'Nancy', age: 37 }
];

var sortByAgeAsc = (a, b) => {
  return b.age - a.age;
};

var sortByAgeDsc = (a, b) => {
  return a.age - b.age;
};

var sortByName = (a, b) => {
  var nameA = a.name.toLowerCase();
  var nameB = b.name.toLowerCase();
  
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }
  
  return 0;
};

var renderListItem = (item) => {
  return `<li><b>Name:</b> ${ item.name } - <b>Age:</b> ${ item.age }</li>`
};

var unsortedNames = items.map((item) => renderListItem(item));
var sortedNamesByAgeAsc = items.sort(sortByAgeAsc).map((item) => renderListItem(item));
var sortedNamesByAgeDsc = items.sort(sortByAgeDsc).map((item) => renderListItem(item));
var sortedNamesByAlpha = items.sort(sortByName).map((item) => renderListItem(item));


document.querySelector('#unsorted-names').innerHTML = unsortedNames.join('');
document.querySelector('#sorted-by-age-asc').innerHTML = sortedNamesByAgeAsc.join('');
document.querySelector('#sorted-by-age-dsc').innerHTML = sortedNamesByAgeDsc.join('');
document.querySelector('#sorted-by-name').innerHTML = sortedNamesByAlpha.join('');

Comments