DEV Community

Cover image for JavaScript Arrays: From Beginner to Advanced
keshav Sandhu
keshav Sandhu

Posted on

JavaScript Arrays: From Beginner to Advanced

Arrays are one of the most fundamental data structures in JavaScript, allowing developers to store and manipulate collections of values. Whether you're just getting started or looking to master more advanced array techniques, this guide will walk you through everything you need to know about JavaScript arrays.


1. What is an Array?

An array is a list-like object that stores multiple values under a single variable name. Each value (element) in an array has a numbered position, called its index, which starts from 0.

let fruits = ["Apple", "Banana", "Orange"];
console.log(fruits[0]); // Output: "Apple"
Enter fullscreen mode Exit fullscreen mode

2. Creating Arrays

Array Literals

The easiest way to create an array is using square brackets ([]):

let numbers = [1, 2, 3, 4, 5];
Enter fullscreen mode Exit fullscreen mode

Using the Array Constructor

You can also create an array using the Array constructor:

let arr = new Array(5); // Creates an empty array with length 5
Enter fullscreen mode Exit fullscreen mode

3. Basic Array Operations

Add Elements

  • Push: Add an element to the end of an array.
  let fruits = ["Apple", "Banana"];
  fruits.push("Orange"); // ["Apple", "Banana", "Orange"]
Enter fullscreen mode Exit fullscreen mode
  • Unshift: Add an element to the beginning.
  fruits.unshift("Mango"); // ["Mango", "Apple", "Banana"]
Enter fullscreen mode Exit fullscreen mode

Remove Elements

  • Pop: Remove the last element.
  fruits.pop(); // Removes "Banana"
Enter fullscreen mode Exit fullscreen mode
  • Shift: Remove the first element.
  fruits.shift(); // Removes "Mango"
Enter fullscreen mode Exit fullscreen mode

4. Accessing and Modifying Elements

Each element in an array can be accessed using its index:

let colors = ["Red", "Green", "Blue"];
console.log(colors[1]); // "Green"
Enter fullscreen mode Exit fullscreen mode

You can also change the value at a specific index:

colors[2] = "Yellow"; // ["Red", "Green", "Yellow"]
Enter fullscreen mode Exit fullscreen mode

5. Iterating Over Arrays

Using for Loop

let numbers = [1, 2, 3];
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}
Enter fullscreen mode Exit fullscreen mode

Using forEach Method

The forEach method executes a function once for each element in the array:

numbers.forEach(num => console.log(num));
Enter fullscreen mode Exit fullscreen mode

6. Array Methods (Intermediate)

map

The map method creates a new array by applying a function to each element.

let doubled = [1, 2, 3].map(num => num * 2); // [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

flatmap

The flatMap() method maps all array elements and creates a new flat array.

const myArr = [1, 2, 3, 4, 5, 6];
const newArr = myArr.flatMap(x => [x, x * 10]); 
// [1,10,2,20,3,30,4,40,5,50,6,60]
Enter fullscreen mode Exit fullscreen mode

filter

Filters the array and returns only the elements that match the condition.

let even = [1, 2, 3, 4].filter(num => num % 2 === 0); // [2, 4]
Enter fullscreen mode Exit fullscreen mode

reduce

Reduces the array to a single value by applying a function to each element.

let sum = [1, 2, 3, 4].reduce((acc, num) => acc + num, 0); // 10
Enter fullscreen mode Exit fullscreen mode

find

Returns the first element that matches a given condition.

let result = [5, 12, 8, 130, 44].find(num => num > 10); // 12
Enter fullscreen mode Exit fullscreen mode

includes

Checks if an array contains a specific element.

let hasApple = ["Banana", "Apple", "Grapes"].includes("Apple"); // true
Enter fullscreen mode Exit fullscreen mode

7. Advanced Array Techniques

Spreading Arrays (...)

The spread operator (...) allows you to easily copy or combine arrays.

let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Array Destructuring

Array destructuring lets you unpack values from arrays into distinct variables.

let [first, second] = [10, 20, 30];
console.log(first);  // 10
console.log(second); // 20
Enter fullscreen mode Exit fullscreen mode

concat

Concatenates two or more arrays.

let arr1 = [1, 2];
let arr2 = [3, 4];
let combined = arr1.concat(arr2); // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

slice

Returns a shallow copy of a portion of an array.

let fruits = ["Banana", "Orange", "Lemon", "Apple"];
let citrus = fruits.slice(1, 3); // ["Orange", "Lemon"]
Enter fullscreen mode Exit fullscreen mode

splice

Adds/removes elements from an array.

let fruits = ["Banana", "Orange", "Apple"];
fruits.splice(1, 0, "Lemon"); // ["Banana", "Lemon", "Orange", "Apple"]
Enter fullscreen mode Exit fullscreen mode

8. Multidimensional Arrays

Arrays can contain other arrays (also known as nested or multidimensional arrays).

let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
console.log(matrix[1][2]); // 6
Enter fullscreen mode Exit fullscreen mode

9. Immutable Array Methods

Some array methods create new arrays without modifying the original array, which can be helpful in functional programming.

  • concat: Combines arrays without modifying the original ones.
  • map: Creates a new array based on the results of a function.
  • filter: Filters the array without changing the original array.

10. Sorting and Reversing

sort

Sorts the elements in an array:

let nums = [30, 1, 21, 7];
nums.sort((a, b) => a - b); // [1, 7, 21, 30]
Enter fullscreen mode Exit fullscreen mode

reverse

Reverses the elements in the array:

nums.reverse(); // [30, 21, 7, 1]
Enter fullscreen mode Exit fullscreen mode

11. Flattening Arrays

Flattening an array means reducing its dimensionality. You can use the flat method to flatten nested arrays.

let arr = [1, 2, [3, 4], [5, [6, 7]]];
console.log(arr.flat(2)); // [1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

12. Removing Duplicates

You can use a Set to remove duplicates from an array:

let arr = [1, 2, 2, 3, 4, 4];
let uniqueArr = [...new Set(arr)]; // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Conclusion

JavaScript arrays are a powerful tool for managing data in your applications. From basic operations like adding/removing elements to more advanced techniques like using map, reduce, and flat, arrays offer a wide range of functionality for developers at any skill level. Practice using these methods, and you'll soon master JavaScript arrays!

Top comments (2)

Collapse
 
mannuelf profile image
Mannuel

flatMap() is cool too, have reached for it a few times.

Collapse
 
keshav___dev profile image
keshav Sandhu

yeah, will add it too thanks✨