Logo
Unit 13 – Advanced Arrays

Advanced Arrays

Duration: 5 minutes

Hello, array aficionados!

As we continue our JavaScript journey, we come across a terrain filled with more intricate array manipulations. Arrays in JavaScript are not just simple lists; they come packed with powerful methods that can transform, filter, and even reduce them into something entirely different.

Let’s dive deeper into these advanced array methods: map, filter, and reduce.

Understanding Advanced Array Methods

Arrays are versatile structures, and with JavaScript’s advanced methods, their potential is vast. Here’s a brief overview:

Map: The map() method creates a new array with the results of calling a function on every element in the calling array.

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]

Filter: The filter() method creates a new array with all elements that pass the test implemented by the provided function.

const values = [5, 12, 8, 130, 44];
const filtered = values.filter(value => value >= 10);
console.log(filtered); // [12, 130, 44]

Reduce: The reduce() method executes a reducer function on each element of the array, resulting in a single output value.

const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, cur) => acc + cur, 0);
console.log(sum); // 10

Exercise

Time for you to harness the power of advanced array methods:

  • Begin with the array: [2, 4, 6, 8, 10].
  • Use map to double each value of the array.
  • Use filter to retain only values greater than 10.
  • Use reduce to sum up the filtered values.

Kickstart with this template:

const initialArray = [2, 4, 6, 8, 10];
// Double the values using map
const doubledArray = initialArray.map(value => value * 2);
// Filter out values less than or equal to 10
const filteredArray = doubledArray.filter(value => value > 10);
// Sum up the filtered values using reduce
const sum = filteredArray.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(doubledArray); // [4, 8, 12, 16, 20]
console.log(filteredArray); // [12, 16, 20]
console.log(sum); // 48

Conclusion

Bravo! You’ve just taken your array manipulation skills to a new level with the powerful map, filter, and reduce methods. Remember, as your datasets grow, these techniques will become invaluable. Keep practicing, keep refining, and you’ll soon be the maestro of array manipulations in JavaScript.

Happy coding, and may your arrays always be in order!

Next Tutorial: Working with the Browser Environment

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!