Skip to content

J053 Functional Programming with Arrays

In this exercise, you will practice working with JavaScript array methods to manipulate and analyze data. You will create functions using either regular functions or lambda expressions for the following methods:

  • map
  • filter
  • sort
  • findIndex

Task

  1. Start with an array of numbers:

    const numbers = [5, 3, 20, 7, 12, 8, 19, 2, 5, 10];
    

  2. Implement the following functions:

  3. Double the numbers using map:

    • Create a function that returns a new array where each number is doubled.
      function doubleNumbers(arr) {
        // Your code here
      }
      
  4. Filter numbers greater than 10 using filter:

    • Create a function that returns a new array containing only the numbers greater than 10.
      function filterGreaterThanTen(arr) {
        // Your code here
      }
      
  5. Sort the numbers in ascending order using sort:

    • Create a function that sorts the numbers in ascending order and returns the sorted array.
      function sortNumbers(arr) {
        // Your code here
      }
      
  6. Find the index of the first number greater than 10 using findIndex:

    • Create a function that returns the index of the first number greater than 10 in the array.
      function findIndexGreaterThanTen(arr) {
        // Your code here
      }
      
  7. Test your functions:

  8. Call each function with the numbers array and print the results.
Solution
const numbers = [5, 3, 20, 7, 12, 8, 19, 2, 5, 10];

// Double the numbers
function doubleNumbers(arr) {
return arr.map(num => num * 2);
}

// Filter numbers greater than 10
function filterGreaterThanTen(arr) {
return arr.filter(num => num > 10);
}

// Sort the numbers in ascending order
function sortNumbers(arr) {
return [...arr].sort((a, b) => a - b);
}

// Find the index of the first number greater than 10
function findIndexGreaterThanTen(arr) {
return arr.findIndex(num => num > 10);
}

// Test the functions
console.log("Original numbers:", numbers);
console.log("Doubled numbers:", doubleNumbers(numbers));
console.log("Numbers greater than 10:", filterGreaterThanTen(numbers));
console.log("Sorted numbers:", sortNumbers(numbers));
console.log("Index of first number greater than 10:", findIndexGreaterThanTen(numbers));