DEV Community

loading...

Array Methods...

danicodes01 profile image daniel knowles ・6 min read






Higher order Functions


What i have learned
so far @ OpSpark


Im a little lazy &...

I β™‘ higherOrderFunctions



What are Higher Order Functions??

  • little robots packed full of information that fly around and make our lives easier?????
  • magic wands that have the ability to change the forms of data structures, objects and values with only a wave and wink!?!!??
  • or! is it as simple as having a friend you know you can always callπŸ“ž on for help?
  • close, close and um, close... Lets take a look below, at what Higher Order Functions are really all about...


do you ever get tired of writing code, over and over again? what if you had a way to take all the repetitive for loops and filtering of data types and wrap them up into nice neat packages, that you can then call on them whenever you need them?

Functions are objects. You can store functions in a variable, you can also store them in a an array. Higher Order Functions are functions that pass functions as arguments to other functions. In hopes that the outer argument will then call your argument function. this is called a callback call back functions are super important in javascript. We are gooing to focus on my favorite Higher Order Functions, Array Callback methods...

Im sure you have seen these methods before. We can use them almost anywere in our code to make things much easier on us. These methods can be used on any data structure. Arrays or Objects alike. With Array Callback Methods you can pass in a function as a argument and run that function once per every element in the array. It creates a new array from that array with the values that met your requirements. Wait so you mean we dont have to first create an empty array, write our for loop, write the logic we want to perform on that array, push those values into the empty array and finally save that array to a variable? Nope, it's much easier if we just use one of JavaScripts built in methods.Let's take a look at a few of the more popular array methods. We will start with forEach.

forEach

The forEach method is much like a for loop. You can pass in a function and then run that function on every element in the array. The main difference between forEach and the other Array Methods we will look at is that forEach does not give us a new array.Instead it just loops over the elements and makes them available for us to do things like log them.Let's say we have an array with some nested objects nested object...

const cats = [ { name: "sandy", cat years: 21, type: "street cat" }, { name: "bug", cat years: 13, type: "house cat" }, { name: "chip", cat years: 26, type: "street cat" }; { name: "ruby", cat years: 25, type: "house cat" } ];

so say we want to print to the console all of the cat names that are found in our list. We can run forEach on the array checking all the elements for the key name...

cats.forEach(cat => console.log(cat.name));

"cat" becomes our place holder that represents each individual element in the array. It focuses on a different element each time through the loop. So if we want to get all the names of the cats we simply use dot notation. What if i need the index you ask? Dont worry, forEach can take in the index as an argument as well. so if you want to see all of the cat objects and there index you could simply say...

cats.forEach((cat, ind) => console.log(ind, cat));

Map

Now we will look at probably my favorite Array Method, Map. Map is like forEach, it accepts a callback, it loops over the array, calling that call back function on every element in the array, but it also makes a new array with those values. We can then save those values to a variable and Presto!! we have a new array with the values we wanted, and all while leaving the original array untouched! lets take a look at some examples with Map. We will use the array of cats above. say we wanted to return a new array with all of the cat ages, multiplied by 2...

const catAgeXtwo = cats.map(cat => cat.catYears * 2);

we now have a new array with those values we wanted, conveniently packed into a variable that we can now use wherever we like... Notice whatever we put into the logic will run for every iteration. sooo just like we multiplied each age by 2, in theory if we wanted a array of 3Β΄s, we could just say...

x = cats.map(cat => 3); console.log(x) // will give us [3,3,3,3];

that would give us an array where all of our cats are now 3. This is because Map takes a value and it maps that value to a the new array

filter

filter creates a new array with all elements that pass the test implemented by the provided function creating a copy with specific targeted elements. so say we want to get all of the cats with ages that are under 24 we can call filter on the cats array like so...

catsUnder24 = cats.filter(cat => cat.catYears < 24);

this will give us back the two objects for the cats that under 24, Sandy and Bug... now lets say we want to get all of the cats that live outside. we can use filter again to filter for "street cat"...

streetCats = cats.filter(cat => cat.type === "street cat");

this will give us the objects for Sandy and Chip.

reduce

Reduce is probably the most confusing of the 4 array methods that we have looked at. Reduce takes the values and reduces them down to a single value. It does this by accepting three arguments. An "accumulator", the current element and an optional "seed". Each time reduce loops over the array it passes the current value into the accumulator value, increasing it each time. The seed acts as a starting point. You can put any value you want as the seed, to be the starting total of your "accumulator". So if your seed starts at 10 you will be adding ten to your final result. Lets get the total ages of all the catYears put together.

totalCatYears = cats.reduce((acc, curr) => acc + curr.catYears, 0);

so with this we see that the total of all of our casts ages is 85. notice the 0 at the end. that is our seed... lets give an example where we want our seed to start with 10...

totalCatYearsPlus10 = cats.reduce((acc, curr) => acc + curr.catYears, 10);

we now get 95 as our total

This is very useful when we want to reduce an array or object down to a single value. I am sure you can find opertunites to use reduce all over the place in your code.

Chaining

Okay so if thats not enough. you can also chain these methods together!!! Let me show you one quick example. Lets take a array of numbers. First lets use map
to multiply the numbers by two. Then lets filter anything that is greater then or equal to 30. Then finally we will get the total of all of those new values with our
reduce method.

const numbers = [1, 45, 23, 12, 8, 43, 6, 10, 15, 5];

const chainedMethods = numbers
.map(num => num * 2)
.filter(num => num >= 30)
.reduce((acc, curr) => acc + curr);

that gives us a grand total of 252! I hope you guys have enjoyed this blog on Array Callback Methods and I encourage you to go out and try some of these methods yourself! Good Luck!




















😺😺😺😺😺
Blog rated by the national cat blog writing society...

Discussion (0)

pic
Editor guide