Mapping out the ranking! (JavaScript)

Have you ever used a map, filter, or reduce function without thinking about it? Many of us who’ve been coding for a while have and we take it’s built in functionality for granted. I know I have. This is an appreciation blog for the wonderful functionality and components built into a coding language that I didn’t have build.

So one cool functionality I discovered built into the higher level functions of several JavaScript functions is the inherent index argument. Pulling the syntax for first three enumerable functions I learned from mozilla…

.map()
let newArray = arr.map(callback(currentValue[, index[, array]]) {
// return element for newArray, after executing something
}[, thisArg]);
.filter()
let newArray = arr.filter(callback(currentValue[, index[, array]]) {
// return element for newArray, if true
}[, thisArg]);
.reduce()
arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])

We can see each of these design patterns have a lot in common. I want to focus on the -> currentValue, [, index] <- section of these functions. Imagine a scenario where people are racing around a track! A very dangerous track, with turtle shells, banana peels, and rockets everywhere! And at the end of the race you want a function to show each person in the race and their position.

One way to do this would be creating an array of hashes, with keys like name and position having values like “Red plumber”, and 1. And then loop over that array of hashes. Pulling out the values by their keys. It could look like this.

let racers = []
let position = 1
function addRacerToRacers(racer){
let racer = {name: racer, position: position)
position++
racers.push(racer)
}
function displayRacers(racers){
for(let i =0; i<racers.length; i++){
let name = racers[i].name
let position = racers[i].position
createRacerCard(name,position)
}
return "Race Completed"
}

This is assuming our createRacerCard function is going to do the mechanical bits of creating and displaying the racers on the users screen, and taking in the arguments of name and position. Knowing the ability to access the index is built into these high level functions we can create a simpler un-nested array and draw out the same values, AND with fewer global variables.

let racers = []
function addRacerToRacers(racer){
racers.push(racer)
}
function displayRacers(racers){
racers.map((racer, index) => createRacerCard(racer, index +1))
}

Being able to access the index in each iteration can be a powerful tool in the right circumstances and it’s as easy as knowing which functions come with it built in, and adding a “, index” in your callback function.