I have no fancy project today. Sorry!

Today was all about learning and practicing. The main thing I learned about today is array methods. It’s not really so much that it’s something new I learned but it’s something that I was reintroduced to today.

So, our lesson for today is, drum roll please, ARRAY METHODS! 😀 

I’m going to talk about 4 in particular.

  • filter()
  • map()
  • sort()
  • reduce()

filter()

The filter method loops through your array and returns a section of your array based on conditions you provide on your code. Here’s an example.

let numbers = [1, 9, 4, 2, 23, 5];

let filteredNumbers = numbers.filter(function(num) {
 if (num % 2 === 0) {
   return num;
 }
});

The resulting array will be:

[4, 2]

map()

The map method also loops through your array and performs an operation on each and every element of the array. It then returns a new array with the exact number of elements as the original array.

let nintendo = ["Mario", "Luigi", "Toad", "Donkey Kong", "Princess Peach"];

let helloNintendo = nintendo.map(function(character) {
 return "Hello " + character;
});

Here’s what hellloNintendo will contain after running the code.

["Hello Mario", "Hello Luigi", "Hello Toad", "Hello Donkey Kong", "Hello Princess Peach"];

sort()

The sort method does exactly what its name implies, it sorts the array into a specific order. In javascript the sorted array is sorted alphabetically from lowest to highest. Also, unlike the previous methods I talked about, sort affects the original array. As an example:

let numbers =[1, 9, 4, 2, 23, 5];

numbers.sort();

This will modify the original array and leave us with.

[1, 2, 23, 4, 5, 9]

To sort by value, you would need to use the optional compare function built in to sort(). That function takes in 2 parameters – the current element and the element right after it. The compare() function compares the value of the 2 elements based on your conditional. If the conditions are true, it reverses the order of the two elements.

let numbers =[1, 9, 4, 2, 23, 5];

numbers.sort(function(num1, num2) {
  return num1 > num2 ? 1 : -1;
});

Below is the result of sorting using the built in compare() function.

[1, 2, 4, 5, 9, 23]

reduce()

The reduce method acts like a summation operation. If you want to add all the values of an array together, this is what you want to use. Here’s an example.

let numbers =[1, 9, 4, 2, 23, 5];

let total = numbers.reduce(function(accumulator, num) {
  return accumulator += num;
});

This will give us the value of total as 44.

So that’s it for today. Tomorrow, I’ll be back to making projects with JS30 working on a Flex Panels Image Gallery.

See you then!

 

 

Day[3] - CSS Variables with JavaScript to Change Properties
Day[5] - I'm believing it...I think I can really code!

Leave a Comment

Your email address will not be published. Required fields are marked *