whenever life put's you in a tough situtation, never say why me! but, try me!

Chapter 5: Arrays

Arrays are a key data structure in JavaScript used to store ordered collections of values. This chapter covers array basics, common array methods, array manipulation techniques, and multidimensional arrays.

Array Basics

What is an Array?

An array in JavaScript is a special type of object used to store multiple values in a single variable. Arrays can hold values of different types, including numbers, strings, and objects. They are indexed collections, where each element has a numerical index starting from 0.

Creating Arrays

You can create arrays using either array literals or the Array constructor.

Array Literal:

let fruits = ["apple", "banana", "orange"];

Array Constructor:

let numbers = new Array(1, 2, 3, 4);

Accessing Elements

You can access array elements using their index.

Example:

let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // Output: apple
console.log(fruits[1]); // Output: banana

Modifying Elements

You can modify array elements by assigning new values to specific indices.

Example:

let fruits = ["apple", "banana", "orange"];
fruits[1] = "mango";

console.log(fruits); // Output: ['apple', 'mango', 'orange']

Array CRUD Operations

Creating (Adding Elements)

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

Example:

let fruits = ["apple", "banana"];
fruits.push("orange"); // Adds 'orange' to the end
fruits.unshift("mango"); // Adds 'mango' to the beginning

console.log(fruits); // Output: ['mango', 'apple', 'banana', 'orange']

Reading (Accessing Elements)

You can access elements using their index as shown earlier.

Updating (Modifying Elements)

You can update elements by assigning a new value to a specific index.

Example:

let fruits = ["apple", "banana", "orange"];
fruits[2] = "pineapple";

console.log(fruits); // Output: ['apple', 'banana', 'pineapple']

Deleting (Removing Elements)

  • pop(): Removes the last element from an array and returns it.
  • shift(): Removes the first element from an array and returns it.
  • splice(): Removes elements from any position and can also add new elements.

Example:

let fruits = ["apple", "banana", "orange"];
let lastFruit = fruits.pop(); // Removes 'orange'
let firstFruit = fruits.shift(); // Removes 'apple'

console.log(lastFruit); // Output: orange
console.log(firstFruit); // Output: apple
console.log(fruits); // Output: ['banana']

Array Methods

JavaScript arrays come with a variety of built-in methods to perform operations on array elements. Here are some of the most commonly used methods:

map()

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

Syntax:

array.map(callback(currentValue, index, array));

Example:

let numbers = [1, 2, 3, 4];
let doubled = numbers.map((x) => x * 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.

Syntax:

array.filter(callback(element, index, array));

Example:

let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter((x) => x % 2 === 0);

console.log(evenNumbers); // Output: [2, 4]

reduce()

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

Syntax:

array.reduce(callback(accumulator, currentValue, index, array), initialValue);

Example:

let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((acc, curr) => acc + curr, 0);

console.log(sum); // Output: 10

find()

The find() method returns the first element in the array that satisfies the provided testing function.

Syntax:

array.find(callback(element, index, array));

Example:

let numbers = [1, 2, 3, 4, 5];
let firstEven = numbers.find((x) => x % 2 === 0);

console.log(firstEven); // Output: 2

Array Manipulation

JavaScript provides several methods to manipulate arrays, allowing you to add, remove, or modify elements.

push()

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Syntax:

array.push(element1, element2, ..., elementN)

Example:

let fruits = ["apple", "banana"];
fruits.push("orange");

console.log(fruits); // Output: ['apple', 'banana', 'orange']

pop()

The pop() method removes the last element from an array and returns that element.

Syntax:

array.pop();

Example:

let fruits = ["apple", "banana", "orange"];
let lastFruit = fruits.pop();

console.log(lastFruit); // Output: orange
console.log(fruits); // Output: ['apple', 'banana']

shift()

The shift() method removes the first element from an array and returns that element.

Syntax:

array.shift();

Example:

let fruits = ["apple", "banana", "orange"];
let firstFruit = fruits.shift();

console.log(firstFruit); // Output: apple
console.log(fruits); // Output: ['banana', 'orange']

unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

Syntax:

array.unshift(element1, element2, ..., elementN)

Example:

let fruits = ["banana", "orange"];
fruits.unshift("apple");

console.log(fruits); // Output: ['apple', 'banana', 'orange']

splice()

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

Syntax:

array.splice(start, deleteCount, item1, item2, ..., itemN)
  • start – The index at which to start changing the array.
  • deleteCount – The number of elements to remove.
  • item1, item2, ..., itemN – The elements to add.

Example:

let fruits = ["apple", "banana", "orange"];
fruits.splice(1, 1, "mango", "pineapple");

console.log(fruits); // Output: ['apple', 'mango', 'pineapple', 'orange']

concat()

The concat() method is used to merge two or more arrays into a new array. It does not modify the original arrays.

Syntax:

array.concat(array1, array2, ..., arrayN)

Example:

let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let combined = array1.concat(array2);

console.log(combined); // Output: [1, 2, 3, 4, 5, 6]

join()

The join() method creates and returns a new string by concatenating all elements of an array, separated by a specified separator.

Syntax:

array.join(separator);

Example:

let fruits = ["apple", "banana", "orange"];
let fruitString = fruits.join(", ");

console.log(fruitString); // Output: "apple, banana, orange"

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) where start and end represent the index positions.

Syntax:

array.slice(start, end);

Example:

let numbers = [1, 2, 3, 4, 5];
let subset = numbers.slice(1, 4);

console.log(subset); // Output: [2, 3, 4]

sort()

The sort() method sorts the elements of an array in place and returns the sorted array. By default, it sorts the elements as strings in ascending order.

Syntax:

array.sort(compareFunction);

Example:

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);

console.log(numbers); // Output: [1, 2, 3, 4, 5]

reverse()

The reverse() method reverses the elements of an array in place.

Syntax:

array.reverse();

Example:

let fruits = ["apple", "banana", "orange"];
fruits.reverse();

console.log(fruits); // Output: ['orange', 'banana', 'apple']

findIndex()

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Returns -1 if no elements satisfy the testing function.

Syntax:

array.findIndex(callback(element, index, array));

Example:

let numbers = [5, 12, 8, 130, 44];
let index = numbers.findIndex((x) => x > 10);

console.log(index); // Output: 1

some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. Returns true if any element passes the test; otherwise, false.

Syntax:

array.some(callback(element, index, array));

Example:

let numbers = [1, 2, 3, 4, 5];
let hasEven = numbers.some((x) => x % 2 === 0);

console.log(hasEven); // Output: true

every()

The every() method tests whether all elements in the array pass the test implemented by the provided function. Returns true if all elements pass the test; otherwise, false.

Syntax:

array.every(callback(element, index, array));

Example:

let numbers = [2, 4, 6, 8];
let allEven = numbers.every((x) => x % 2 === 0);

console.log(allEven); // Output: true

fill()

The fill() method changes all elements in an array to a static value from a start index to an end index (end not included). The original array is modified.

Syntax:

array.fill(value, start, end);

Example:

let numbers = [1, 2, 3, 4];
numbers.fill(0, 2);

console.log(numbers); // Output: [1, 2, 0, 0]

copyWithin()

The copyWithin() method copies a sequence of array elements within the array to the position starting at the target index.

Syntax:

array.copyWithin(target, start, end);

Example:

let numbers = [1, 2, 3, 4, 5];
numbers.copyWithin(0, 3, 5);

console.log(numbers); // Output: [4, 5, 3, 4, 5]

flat()

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Syntax:

array.flat(depth);

Example:

let nestedArray = [1, [2, [3, 4]]];
let flatArray = nestedArray.flat(2);

console.log(flatArray); // Output: [1, 2, 3, 4]

flatMap()

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array.

Syntax:

array.flatMap(callback(element, index, array));

Example:

let arrays = [
  [1, 2],
  [3, 4],
  [5, 6],
];
let flattened = arrays.flatMap((arr) => arr);

console.log(flattened); // Output: [1, 2, 3, 4, 5, 6]

Multidimensional Arrays

A multidimensional array is an array of arrays, which allows you to represent more complex data structures, such as matrices or grids.

Example of a 2D Array:

let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

console.log(matrix[0][1]); // Output: 2
console.log(matrix[2][2]); // Output: 9

In this example, matrix is a 2D array where each element is an array itself. You can access individual elements using two indices, where the first index selects the row and the second index selects the column.

Example of Iterating Over a 2D Array:

for (let row = 0; row < matrix.length; row++) {
  for (let col = 0; col < matrix[row].length; col++) {
    console.log(matrix[row][col]);
  }
}

This example iterates over each element in the 2D array and logs it to the console.

Certainly! Let's expand on Chapter 5 by including additional array methods to give you a more comprehensive understanding of array operations in JavaScript.