Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

JavaScript Essentials - Advanced Arrays

Advanced array methods and operations

Arrays are a fundamental part of JavaScript. This tutorial delves into advanced methods and operations that help you manipulate arrays more effectively.

Key Points:

  • Understand and utilize higher-order functions like map, filter, and reduce.
  • Manipulate arrays with methods like splice, slice, and concat.
  • Use array methods to write clean, efficient, and readable code.

Array Methods

Map

The map method creates a new array with the results of calling a provided function on every element in the calling array.


const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [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 numbers = [1, 2, 3, 4, 5];
const even = numbers.filter(num => num % 2 === 0);
console.log(even); // Output: [2, 4]
                

Reduce

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


const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // Output: 10
                

Array Manipulation

Splice

The splice method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.


const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 1, "Lemon", "Kiwi");
console.log(fruits); // Output: ["Banana", "Orange", "Lemon", "Kiwi", "Mango"]
                

Slice

The slice method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included).


const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);
console.log(citrus); // Output: ["Orange", "Lemon"]
                

Concat

The concat method is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array.


const array1 = ["Cecilie", "Lone"];
const array2 = ["Emil", "Tobias", "Linus"];
const children = array1.concat(array2);
console.log(children); // Output: ["Cecilie", "Lone", "Emil", "Tobias", "Linus"]
                

Summary

In this tutorial, you learned about advanced array methods and operations in JavaScript. Mastering these methods will allow you to handle array data more efficiently and write more powerful JavaScript code.