JavaScript Functional Programming (Solution to Code Challenge #11)
Publikováno: 22.6.2018
Tried the code challenge #11? In that, we delved into solving basic array problems using array methods s...
Tried the code challenge #11? In that, we delved into solving basic array problems using array methods such as map()
, reduce()
, filter()
etc.
You can find the awesome entries in the comment section of the post as well on Twitter using the hashtag #scotchchallenge. Also, you see some other fantastic submissions for the challenge if you check out the Scotch Slack Group as well as this Spectrum thread for the challenge.
The Challenge
Functional programming is a style in writing programs which utilizes functions and function evaluations to carry out computations.
In this challenge, we were tasked with solving problems by manipulating given arrays in a base codepen. This challenge will be solved using native array methods to manipulate the given array.
Methods are properties of a given data type which basically contains function definitions
With methods, we are basically applying pre-created functions on the array to achieve our desired result.
The Base
No HTML and CSS code is provided for this challenge as it requires no view. However, JavaScript code is provided containing the arrays to be manipulated - texasss, newieyork, and vegzas. Problems to be solved are also written in comments after each array.
While this challenge has no view, results will be logged to the console.
You can find the base codepen provided below.
The Technique
Basically solving the problems tied to each array is pretty straight-forward as we directly applied native array methods from:
- filter()
- map()
- sort()
- reduce()
Care is taken to understand which methods are mutating and also non-mutating
Mutating methods make changes to the original array whilst retaining the variable name whereas non-mutating methods create a new array with the result of the function application.
Array 1: texasss
On this array we are required to:
Find all users older than 24
This is done using the filter()
function to return all objects whose age property value is less than 24. The result is logged to the console.
const users24 = texasss.filter(val => {
return val.age > 24
});
console.log(users24)
Find the total age of all users
To solve this, first, we utilized the map()
method to iterate through each object in the array, fetch the age of each user then use the reduce()
method to sum up all the age values into a single value.
const totalAge = texasss.map((user)=> user.age).reduce((prev, next)=> prev + next)
console.log(totalAge)
List all users in the US
Similarly using the filter()
option we traverse the array and fetch all users whose boolean value of the us
property resolves to true.
const usersUS = texasss.filter(user => {
return user.us == true;
})
console.log(usersUS)
Array 2: newieyork
In this array we'll be taking things a bit further with:
List all users in US in ascending order
To achieve this we'll use the sort()
function. Sorting an array of objects using particular properties such as name or age can be tricky as compared to sorting array items with strings.
For us to sort the array, we will be creating a comparison function first converts the name values to be enumerated to lowercase. A ternary operator is used to conditionally return a value depending on which enumerable property is higher when compared.
const sortedUS = newieyork
sortedUS.sort((a, b) => {
const x = a.name.toLowerCase()
const y = b.name.toLowerCase()
return x < y ? -1 : 1
})
console.log(sortedUS)
Sort all users by age
Sorting all users by age is more straightforward as enumerating numerical values are quite simpler. The sort()
method is used to arrange the users according to their age.
const sortedAge = newieyork
sortedAge.sort((a, b) => {
return a.age - b.age
})
console.log(sortedAge)
List all female coders
In order to solve this, we employ the filter()
function to pick out all users with the gender of f
.
const femaleCoders = newieyork.filter(val=>{
return val.gender == 'f'
})
console.log(femaleCoders)
Array 3: vegzas
Taking it one step further again, we'll be solving the last set of challenges.
Find the total age of male coders under 25
To achieve this we employ three levels of function application, the steps are:
- Filter the array to match gender and age requirements of
m
and25
respectively. - Traverse the array and return the age of each user.
- Find the sum of all the age fetched.
const maleCodersAge = vegzas
.filter(val => val.gender == 'm' && val.age < 25)
.map(male => male.age)
.reduce((prev, next)=> prev + next)
console.log(maleCodersAge)
List all male coders over 30
Here we filter the array and return users with a gender of m
and over the age of 30.
const maleCodersOver30 = vegzas.filter(val => {
return val.age > 30 && val.gender == 'm'
})
console.log(maleCodersOver30)
Find the total age of everyone in texasss, newieyork and vegzas combined.
Down to the last challenge, we are required to find the total age of all the users in all the arrays. We achieved this by:
- Creating an empty array to hold all the age of all users from all the arrays.
- Traverse each array using the
map()
method and return the age of each user. - Add each age fetched into the empty array created using the
push()
method. - Use the
reduce()
method to sum all the ages pushed into the now populated array.
const totalAges = []
texasss.map(val => totalAges.push(val.age))
newieyork.map(val => totalAges.push(val.age))
vegzas.map(val => totalAges.push(val.age))
const ageSum = totalAges.reduce((prev, next)=> prev + next)
console.log(ageSum)
You can find the final product here: https://codepen.io/Chuloo/pen/JZWVPJ
Conclusion
In this challenge, we used various in-built array methods to solve these challenges. You can try out other array methods and functions, also dig the difference between methods with similar capabilities. Feel free to leave your comments and suggestions in the comment section of this post and watch out for the next challenge. Happy coding!