JavaScript Arrays

JavaScript Arrays

JavaScript Arrays

An array is a special type of object used to store multiple values in a single variable. In JavaScript, arrays can hold items of different types (numbers, strings, objects, other arrays, etc.), and they are indexed by numbers starting from 0.

1️⃣ Creating Arrays

You can create arrays in a few different ways:

1.1 Using Array Literals (Most Common)

let fruits = ['Apple', 'Banana', 'Cherry']; console.log(fruits); // ["Apple", "Banana", "Cherry"]

1.2 Using the Array Constructor

let numbers = new Array(1, 2, 3, 4, 5); console.log(numbers); // [1, 2, 3, 4, 5]

1.3 Creating an Empty Array

let emptyArray = []; console.log(emptyArray); // []

Or using the Array constructor:

let emptyArray = new Array(); console.log(emptyArray); // []

2️⃣ Accessing Array Elements

You access the elements in an array using the index (starting from 0):

let fruits = ['Apple', 'Banana', 'Cherry']; console.log(fruits[0]); // "Apple" console.log(fruits[1]); // "Banana"

You can also use negative indices to access elements from the end of the array (using at() method):

console.log(fruits.at(-1)); // "Cherry" (last element) console.log(fruits.at(-2)); // "Banana" (second to last element)

3️⃣ Modifying Arrays

You can modify the contents of an array directly by using the index:

let fruits = ['Apple', 'Banana', 'Cherry']; fruits[1] = 'Mango'; // Modify element at index 1 console.log(fruits); // ["Apple", "Mango", "Cherry"]

4️⃣ Array Methods

JavaScript provides several built-in methods to manipulate arrays. Here are some of the most commonly used ones:

4.1 Adding Elements

  • push(): Adds one or more elements to the end of the array.

    let fruits = ['Apple', 'Banana']; fruits.push('Cherry'); console.log(fruits); // ["Apple", "Banana", "Cherry"]
  • unshift(): Adds one or more elements to the beginning of the array.

    let fruits = ['Banana', 'Cherry']; fruits.unshift('Apple'); console.log(fruits); // ["Apple", "Banana", "Cherry"]

4.2 Removing Elements

  • pop(): Removes the last element from the array and returns it.

    let fruits = ['Apple', 'Banana', 'Cherry']; let lastFruit = fruits.pop(); console.log(lastFruit); // "Cherry" console.log(fruits); // ["Apple", "Banana"]
  • shift(): Removes the first element from the array and returns it.

    let fruits = ['Apple', 'Banana', 'Cherry']; let firstFruit = fruits.shift(); console.log(firstFruit); // "Apple" console.log(fruits); // ["Banana", "Cherry"]

4.3 Modifying Elements at Specific Index

  • splice(): Adds/removes elements at a specific index.

    let fruits = ['Apple', 'Banana', 'Cherry']; fruits.splice(1, 1, 'Mango'); // Remove 1 element at index 1 and add 'Mango' console.log(fruits); // ["Apple", "Mango", "Cherry"]

    Syntax: array.splice(startIndex, deleteCount, item1, item2, ...)

4.4 Finding Elements

  • indexOf(): Returns the index of the first occurrence of a specified element, or -1 if not found.

    let fruits = ['Apple', 'Banana', 'Cherry']; console.log(fruits.indexOf('Banana')); // 1 console.log(fruits.indexOf('Mango')); // -1
  • includes(): Returns true if the array contains a specified element, otherwise false.

    let fruits = ['Apple', 'Banana', 'Cherry']; console.log(fruits.includes('Banana')); // true console.log(fruits.includes('Mango')); // false

4.5 Iterating Over Arrays

  • forEach(): Executes a provided function once for each element in the array.

    let fruits = ['Apple', 'Banana', 'Cherry']; fruits.forEach(function(fruit) { console.log(fruit); });
  • map(): Creates a new array populated with the results of calling a provided function on every element in the array.

    let numbers = [1, 2, 3]; let squares = numbers.map(num => num * num); console.log(squares); // [1, 4, 9]
  • filter(): Creates a new array with all elements that pass the test implemented by the provided function.

    let numbers = [1, 2, 3, 4, 5]; let evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // [2, 4]
  • reduce(): Executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

    let numbers = [1, 2, 3, 4]; let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // 10

4.6 Transforming Arrays

  • sort(): Sorts the elements of the array in place (can be used to sort strings and numbers).

    let numbers = [4, 2, 5, 1, 3]; numbers.sort(); console.log(numbers); // [1, 2, 3, 4, 5]
  • reverse(): Reverses the order of the elements in the array.

    let numbers = [1, 2, 3]; numbers.reverse(); console.log(numbers); // [3, 2, 1]

4.7 Flattening Arrays

  • flat(): Flattens nested arrays into a single array.

    let nestedArray = [1, [2, 3], [4, [5, 6]]]; let flatArray = nestedArray.flat(2); // Flattens two levels console.log(flatArray); // [1, 2, 3, 4, 5, 6]

5️⃣ Multidimensional Arrays

You can have arrays of arrays (multi-dimensional arrays). These are common when working with matrices or complex data structures.

let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; console.log(matrix[0][0]); // 1 (first element of the first array) console.log(matrix[2][1]); // 8 (second element of the third array)

6️⃣ Array Destructuring

You can also destructure arrays to assign values to variables:

let colors = ['Red', 'Green', 'Blue']; let [first, second] = colors; console.log(first); // "Red" console.log(second); // "Green"

You can skip elements and assign them directly:

let [first, , third] = colors; console.log(first); // "Red" console.log(third); // "Blue"

7️⃣ Conclusion

Arrays are a fundamental part of JavaScript that allows you to store multiple values in a single variable and perform various operations on them. They are highly flexible and come with a wide range of built-in methods for sorting, iterating, and modifying the data they hold.

Let me know if you'd like more examples or explanations! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close