DEV Community

Jacob Evans
Jacob Evans

Posted on • Edited on

6

JavaScript Useful Array Methods! Part 1

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! :)

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay