DEV Community

loading...

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']
Enter fullscreen mode Exit fullscreen mode

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`)
console.log(newArrayMap) 
// [ 'crocodile in zoo', 'gorilla in zoo', 'lion in zoo', 'wolf in zoo' ]
Enter fullscreen mode Exit fullscreen mode

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'))
console.log(newArrayFilter) 
// [ 'gorilla in zoo', 'lion in zoo', 'wolf in zoo' ]
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)

pic
Editor guide