Using a high order function to filter a JavaScript array

Published on 2019-11-15 • Modified on 2019-11-15

This is an example of modern usage of JavaScript and functional programming you must know to produce concise and readable code. In this case, we filter an array on one of the properties of the objects it contains. Then, we display the labels of the filtered array. The goal is to avoid using loops and creating new functions.


<script>
    // Open your JavaScript console in order to check the execution of this code. (type: todos, isUrgent, urgents)
    "use strict";
    const todos = [
        { label: 'Call mum', type: 'todo', isUrgent: true },
        { label: 'Buy food', type: 'tobuy', isUrgent: false },
        { label: 'Write a new snippet', type: 'todo', isUrgent: true }
    ];
    const isUrgent = todo => todo.isUrgent;
    const urgents = todos.filter(isUrgent);
    console.log('Urgent todos are: '+urgents.map(todo => todo.label).join(', ')); // That's it! 😁
</script>

 More on Stackoverflow  More on the web