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:
mapfiltersortfindIndex
Task
-
Start with an array of numbers:
-
Implement the following functions:
-
Double the numbers using
map:- Create a function that returns a new array where each number is doubled.
-
Filter numbers greater than 10 using
filter:- Create a function that returns a new array containing only the numbers greater than 10.
-
Sort the numbers in ascending order using
sort:- Create a function that sorts the numbers in ascending order and returns the sorted array.
-
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.
-
Test your functions:
- Call each function with the
numbersarray 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));