JavaScript Useful Array Methods! Part 1

jacobmgevans profile image Jacob Evans Updated on ・2 min read

Examples & Scenerios

Twitter: @jacobmgevans
So it is still a work in progress but someone wanted some simple examples of a few commonly used array methods. I plan on explaining each one in more detail.

const arrayOfAnimals = ['crocodile', 'gorilla', 'lion', 'wolf']

So we need to make a list of animals that are in the zoo and the list will be rendered
directly after updating the list we are given!

const newArrayMap = arrayOfAnimals.map(animal => `${animal} in zoo`)
// [ 'crocodile in zoo', 'gorilla in zoo', 'lion in zoo', 'wolf in zoo' ]

OH NO! We added an animal to the list that actually is no longer in the Zoo!
Lets just remove it with .filter()

const newArrayFilter = newArrayMap.filter(animalInZoo => !animalInZoo.includes('crocodile'))
// [ 'gorilla in zoo', 'lion in zoo', 'wolf in zoo' ]

So we were also given an object with numbers as values...? Oh! its how many of each of those animals are at the zoo and the zookeeper wants a total of all the animals!? I have an idea of how to do this...I think lol

const dataSheetAnimalCount = {
    'crocodile': 0, 
    'gorilla': 3, 
    'lion': 8, 
    'wolf': 10

Alright we have an array of the animal counts... Now what?
If interested in Object built-ins check out this article :)
I am going to use .reduce() to get the total through aggregation of previous value returned with current value of element that reduce is on in the array.

const getValuesFromObject = Object.values(dataSheetAnimalCount) 
console.log(getValuesFromObject) // [0, 3, 8, 10]
const totalAnimalsInZoo = getValuesFromObject.reduce((aggregatedValue, currentValue) => aggregatedValue + currentValue)
console.log(totalAnimalsInZoo) // 21

Seems like that is all we needed to do with the data, for today at least! :)

Posted on by:

jacobmgevans profile

Jacob Evans


Associate Software Engineer @ JP Morgan & Chase | Air Force Veteran | Hardware Enthusiast | Outdoorsman | INTJ | Create React App contributor


Editor guide