Wednesday, December 25, 2019

Sorted to do list in JavaScript

JavaScript is a wonderful language as you may discover in the JavaScript for beginners - learn by doing course.

Here is a short working example on how we can easily sort todos saved inside an array:

The initial HTML markup:
<input id="myInput" type="text" /><button id="Add"> Add new LI </button>
<ul class="todoList"></ul>

<script>
// initial array to hold the todos
const todos = [];

// we have helper function for doing the actual sorting
const doSort = (todos) => {
return todos
// .map(todo => todo.toLowerCase()) // make all the items lowercase
.sort((a, b) => {
// compare 2 words letter by letter
if (a.value > b.value) { return 1; } // when the first letter is after the second
if (a.value < b.value) { return -1; } // when the second letter is before the second
return 0; // if both letters are the same
 }) 
} // attach event listener to the Add button document.querySelector('#Add').addEventListener('click', () => {

// get what's inside the input
const data = document.querySelector('#myInput');

// push the new todo into the todos array
todos.push(data.value);

// create additional helper array with object values and indexes
var mapped = todos.map(
(el, i) => ({ index: i, value: el.toLowerCase() })
);

// sort the todos
const sortedTodos = doSort(mapped)
// restore the originals from the todos array
.map(el => todos[el.index]);

// display the sorted totos
todoList.innerHTML = sortedTodos.map(todo => '<li>' + todo + '</li>').join('');

// clear the value of the input
data.value = '';
});

//get reference to the todoList
const todoList = document.querySelector('.todoList');

</script>

Congratulations!

Resources:

JavaScript for beginners - learn by doing

Subscribe To My Channel for updates