Real-life example of array
Imagine you are making a to-do list for the day. Each task is written in order, and you can add new tasks, remove completed ones, or check a specific task.
In JavaScript, an array works the same way. It stores multiple values in a single variable, allowing you to access, modify, and organize them efficiently.
What is an Array?
An array is a special type of object used to store multiple values in a single variable. It is an ordered collection of elements, where each element can be accessed using its index. In JavaScript, arrays can store values of different types, such as strings, numbers, objects, function, or even other arrays.
Example:
let arr = [1, 2, 3, 4, 5];
console.log(typeof arr) // Output : object
console.log(arr[0]); // Output: 1
console.log(arr[2]); // Output: 3
let arr1 = [
null,
"hello",
{ name: "Prakash" },
function myName() {
console.log("Hi");
},
[1, 2, 3, 4]
];
// Accessing the function element in the array and invoking it.
arr1[3](); // Output: "Hi"
console.log(arr1[2].name) // Output: "Prakash"
console.log(arr1[4][2]) // Output: 3
How Can We Create an Array?
There are several ways to create an array in JavaScript:
- Using Array Literals: The most common and simplest way to create an array.
- Using the Array Constructor: You can also use the built-in
Arrayconstructor. - Using the
Array.of()Method: Creates a new Array instance with a variable number of elements. - Using the
Array.from()Method: Creates a new array from an iterable object or array-like object.
Note : We will understand Array Literals, rest we will understand later.
Examples:
// Using Array Literal
let arr1 = [1, 2, 3];
console.log(arr1) // [ 1, 2, 3 ]
// Using Array Constructor
let arr2 = new Array(4, 5, 6);
console.log(arr2) // [ 4, 5, 6 ]
// Using Array.of()
let arr3 = Array.of(7, 8, 9);
console.log(arr3) // [ 7, 8, 9 ]
// Using Array.from()
let arr4 = Array.from("Hello");
console.log(arr4); // ["H", "e", "l", "l", "o"]Mutable And Immutable
- Mutable: A mutable array can be changed after it is created. The state of the array can be modified directly.
// Example of mutable array
let arr = [1, 2, 3];
arr.push(4); // We modify the array by adding a new element
console.log(arr); // Output: [1, 2, 3, 4]- Immutable: An immutable array cannot be changed after it is created. To modify the array, a new one must be created instead.
// Example of immutable array
let arr1 = [1, 2, 3];
let arr2=[6,7]
let newArr = arr1.concat(arr2); // Instead of modifying, we create a new array
console.log(newArr); // Output: [1, 2, 3, 6, 7]
console.log(arr1); // Output: [1, 2,3] - Original array remains unchangedAll Array Methods with Examples
Here are some commonly used array methods in JavaScript:
length: Returns the number of elements in an array. You can also modify it to change the array's size.
let arr = [1, 2, 3, 4];
console.log(arr.length); // Output: 4
// Setting length to 0 empties the array, means delete all element from array.
arr.length = 0;
console.log(arr); // Output: []
// Dreasing length means deleting from end.
let arr2=[1,2,3,4]
arr2.length=2
console.log(arr2) // Output : [1,2]
// Increasing the length adds empty slots (undefined values) at the end
let arr3=[1,2,3,4]
arr3.length=7
console.log(arr3) // Output : [ 1, 2, 3, 4, <3 empty items> ]
Note : Changing the length property of an array adjusts the number of elements it contains: decreasing the length removes elements from the end, increasing the length adds empty slots (undefined values) at the end, and setting the length to 0 clears the array entirely. This works because JavaScript arrays are dynamically sized.
push(): Adds one or more elements to the end of an array.let arr = [1, 2, 3];
arr.push(4); // adding one element
console.log(arr); // Output: [1, 2, 3, 4]
let arr1=[2,3]
arr1.push(4,6,7) // adding more than one element
console.log(arr1) // Output: [2,3,4,6,7]
pop(): Removes the last element from an array and returns it.let arr = [1, 2, 3];
arr.pop();
console.log(arr); // Output: [1, 2]shift(): Removes the first element from an array and returns it.let arr = [1, 2, 3];
arr.shift();
console.log(arr); // Output: [2, 3]unshift(): Adds one or more elements to the beginning of an array.let arr = [1, 2, 3];
arr.unshift(0); // adding one element
console.log(arr); // Output: [0, 1, 2, 3]
let arr1 = [1, 2, 3];
arr1.unshift(5,6,7); // adding more than one element
console.log(arr1); // Output: [ 5, 6, 7, 1, 2, 3 ]
lastIndexOf(): Returns the last index of the specified element in the array. If the element is not found, it returns -1.let arr = [1, 2, 3, 2, 4];
let result = arr.lastIndexOf(2);
console.log(result); // Output: 3splice()***: Adds, removes, or replaces elements in an array at a specific position.// Initial array
let arr = [1, 2, 3, 4];
// Using splice to modify the array
// Syntax: array.splice(startIndex, deleteCount, ...itemsToAdd)
// Remove 1 element at index 2 and insert 5 at the same position
arr.splice(2, 1, 5);
console.log(arr); // Output: [1, 2, 5, 4]
// Example 2: Only removing elements
arr.splice(1, 2); // Remove 2 elements starting from index 1
console.log(arr); // Output: [1, 4]
// Example 3: Adding elements without removal
arr.splice(1, 0, 6, 7); // Insert 6 and 7 at index 1
console.log(arr); // Output: [1, 6, 7, 4]
Explanation:
The splice() method is a powerful tool in JavaScript for modifying arrays. It works with three parameters:
startIndex: The position in the array where changes begin (0-based index).deleteCount: The number of elements to remove from the array. If set to0, no elements are removed....itemsToAdd: (Optional) Elements to be added at the specifiedstartIndex. You can add as many as needed.
The method modifies the original array directly and returns an array of the removed elements, if any.
slice(): Returns a shallow copy of a portion of an array, without modifying the original array. It takes two parameters:- start (optional): The index where extraction begins (inclusive).
- end (optional): The index where extraction stops (exclusive). If omitted, it slices till the end of the array.
let arr = [1, 2, 3, 4, 5];
// Without start and end index
let newArray = arr.slice();
console.log(newArray); // Output: [1, 2, 3, 4, 5]
// Extract elements from index 1 to index 3 (excluding 3)
let newArr = arr.slice(1, 3);
console.log(newArr); // Output: [2, 3]
// If only one argument is passed, it slices from that index to the end
let newArr2 = arr.slice(2);
console.log(newArr2); // Output: [3, 4, 5]
// Using negative indices (counts from the end)
let newArr3 = arr.slice(-3, -1);
console.log(newArr3); // Output: [3, 4]
// Original array remains unchanged
console.log(arr); // Output: [1, 2, 3, 4, 5]copyWithin():The copyWithin() method shallow copies a portion of an array to another location within the same array without changing the array's length. It allows you to copy elements from one part of the array to another, effectively modifying the original array. The method takes three arguments: the target index, the start index, and the end index (optional). The elements between the start and end indices are copied and placed at the target index.Syntax : array.copyWithin(target, start, end);
// Example of using copyWithin() to copy part of an array to another location
let arr = [1, 2, 3, 4, 5];
// Copy elements from index 0 to index 2 and place them starting at index 3
arr.copyWithin(3, 0, 2);
console.log(arr); // Output: [1, 2, 3, 1, 2]
// Explanation: The copyWithin() method copies the first two elements [1, 2] from the beginning of the array (index 0 to 2) and places them starting at index 3.
// The array is modified in-place, so the result is [1, 2, 3, 1, 2]
// Example without specifying the end index (defaults to the array's length)
let arr2 = [10, 20, 30, 40, 50];
arr2.copyWithin(1, 2);
console.log(arr2); // Output: [10, 30, 40, 40, 50]
// Explanation: The copyWithin() method copies elements starting from index 2 (i.e., [30, 40]) to the target index 1.
// The array is modified to [10, 30, 40, 40, 50]
// Example of copying with negative indices
let arr3 = [1, 2, 3, 4, 5];
arr3.copyWithin(-2, -4, -1);
console.log(arr3); // Output: [1, 2, 3, 3, 4]
// Explanation: Negative indices refer to positions counting from the end of the array.
// The method copies elements starting from index -4 (i.e., [2, 3]) and places them at index -2 (positions 3 and 4).
concat(): The concat() method is used to merge two or more arrays into a new array. It does not modify the original arrays, but instead, it returns a new array that contains all the elements from the input arrays.let arr1 = [1, 2];
let arr2 = [3, 4];
console.log(arr1) // Output: [1, 2]
let newArr = arr1.concat(arr2);
console.log(newArr); // Output: [1, 2, 3, 4]join(): The join() method combines all elements of an array into a single string, separated by a specified delimiter. If no delimiter is provided, the elements are joined with a comma by default.Syntax
arr.join('seperator')
Example
let arr = ['a', 'b', 'c'];
let result = arr.join('-');
console.log(result); // Output: "a-b-c"Array.isArray(): Checks if the given value is an array. It returns true if the value is an array, and false otherwise.let arr = [1, 2, 3];
let result = Array.isArray(arr);
console.log(result); // Output: true
let notArray = { name: "John" };
let result = Array.isArray(notArray);
console.log(result); // Output: falsekeys(): Returns a new array iterator object that contains the keys (indices) of the array.let arr = ['a', 'b', 'c'];
let result = arr.keys();
console.log(result) // Ouptut : Object [Array Iterator] {}
console.log(Array.from(result)); // Output: [0, 1, 2]values(): Returns a new array iterator object that contains the values of the array.let arr = ['a', 'b', 'c'];
let result = arr.values();
console.log(result) // Ouptut : Object [Array Iterator] {}
console.log(Array.from(result)); // Output: ['a', 'b', 'c']entries(): Returns a new array iterator object that contains the key/value pairs of the array.let arr = ['a', 'b', 'c'];
let result = arr.entries();
console.log(result) // Ouptut : Object [Array Iterator] {}
console.log(Array.from(result)); // Output: [[0, 'a'], [1, 'b'], [2, 'c']]toString(): Returns a string representing the array and its elements, joined by commas.let arr = [1, 2, 3];
let result = arr.toString();
console.log(result); // Output: "1,2,3"at(): Returns the element at the specified index, allowing negative indices.let arr = [1, 2, 3];
let result = arr.at(-1);
console.log(result); // Output: 3flat():The flat() method is used to flatten a nested array into a single array. It removes nested arrays and combines their elements into one array. By default, it flattens one level of nesting, but you can specify how deep to flatten.// Example of using flat() to flatten a nested array
let arr = [1, [2, 3], [4, 5]]; // Nested array with two subarrays
// Flattening the array by one level
let result = arr.flat();
console.log(result); // Output: [1, 2, 3, 4, 5]
// Explanation: The flat() method flattens the array by one level, resulting in a single array with all elements.
// Example of double nested array:
let doubleNestedArr = [1, [2, [3, 4]], [5, 6]]; // Nested array with two levels of nesting
// Flattening the array by one level
let result1 = doubleNestedArr.flat();
console.log(result1); // Output: [1, 2, [3, 4], 5, 6]
// Flattening the array by two levels
let result2 = doubleNestedArr.flat(2);
console.log(result2); // Output: [1, 2, 3, 4, 5, 6]
// Explanation: The flat(2) method flattens the array by two levels, fully combining all the elements into a single array.
flatMap():The flatMap() method first maps each element using a provided function, and then it flattens the result by one level. It is a combination of map() and flat(). The difference from using map() alone is that the result of the function is automatically flattened, making it useful for transforming and reducing the depth of nested arrays.// Example of using flatMap() to map and flatten the array
let arr = [1, 2]; // Initial array
// Using flatMap to map each element to a new array and flatten the result
let result = arr.flatMap(x => [x, x * 2]);
console.log(result); // Output: [1, 2, 2, 4]
// Explanation: The flatMap() method first maps each element of the array, and then flattens the result.
// [1, 2] becomes [1, 2] and [2, 4], resulting in [1, 2, 2, 4]
// Example with a nested structure:
let arr2 = [1, 2, 3];
let result2 = arr2.flatMap(x => [x, x + 1]);
console.log(result2); // Output: [1, 2, 2, 3, 3, 4]
// Explanation: The flatMap() method first maps each element to a pair [x, x + 1] and then flattens the result.
// [1, 2], [2, 3], [3, 4] is flattened into a single array: [1, 2, 2, 3, 3, 4]
fill(): Fills elements in an array with a static value from a start index to an end index.// Initial array
let arr = [1, 2, 3, 4, 5];
// Example 1: Fill the entire array with 0
arr.fill(0);
console.log(arr); // Output: [0, 0, 0, 0, 0]
// Example 2: Fill part of the array with 9 (from index 1 to 3, excluding index 3)
arr.fill(9, 1, 3);
console.log(arr); // Output: [0, 9, 9, 0, 0]
// Example 3: Fill part of the array starting from index 2 to the end
arr.fill(7, 2);
console.log(arr); // Output: [0, 9, 7, 7, 7]
Explanation:
The fill() method allows you to replace elements in an array with a specified static value. It works with three parameters:
value: The value used to fill the array or a portion of it.start: (Optional) The starting index (inclusive) where filling begins. Default is0.end: (Optional) The ending index (exclusive) where filling stops. Default is the array's length.
The fill() method modifies the original array directly and is useful for initializing or resetting arrays with specific values.
sort():The sort() method sorts the elements of an array in place, modifying the original array. By default, the sorting is done in lexicographical (string) order, which can produce unexpected results for arrays of numbers. You can pass a custom sorting function to sort elements in different ways, such as numerically or by custom criteria.// Example of using sort() to sort an array of numbers
let arr = [4, 2, 3, 1]; // Original array
// By default, sort() converts elements to strings and sorts them lexicographically
arr.sort();
console.log(arr); // Output: [1, 2, 3, 4]
// Explanation: In default sort, 4 comes before 2, so they are sorted as strings instead of numbers
// To sort numerically, pass a compare function
let numArr = [4, 2, 3, 1];
// Sorting numerically in ascending order using compare function
numArr.sort((a, b) => a - b);
console.log(numArr); // Output: [1, 2, 3, 4]
// Explanation: The compare function (a, b) => a - b ensures numerical sorting
reverse():The reverse() method reverses the order of the elements in an array in place, meaning it modifies the original array. It does not return a new array, but rather the reversed version of the original array.// Example of using reverse() to reverse the order of an array
let arr = [1, 2, 3]; // Original array
// Reversing the array in place
arr.reverse();
console.log(arr); // Output: [3, 2, 1]
// Explanation: The reverse() method reverses the array in place, so the elements are rearranged in reverse order.
includes():The includes() method checks if a specified element is present in an array. It returns a boolean value: true if the element is found, and false if the element is not found.// Example of using includes() to check if an array contains a specific element
let arr = [1, 2, 3]; // Original array
// Checking if the array contains the element 2
let result = arr.includes(2);
console.log(result); // Output: true
// Explanation: The includes() method checks if the element '2' is present in the array, and returns true because it is found.
indexOf():The indexOf() method returns the first index at which a specified element is found in the array. If the element is not found, it returns -1.// Example of using indexOf() to find the first index of an element in an array
let arr = [1, 2, 3]; // Original array
// Finding the index of the element 2
let result = arr.indexOf(2);
console.log(result); // Output: 1
// Explanation: The indexOf() method returns the first index of the element '2' in the array, which is 1.
Higher-Order Array Methods
Note: The following array methods are higher-order functions that take callback functions as arguments. We will discuss these in detail in a separate article on Higher-Order Functions. For now, here's a brief overview:
forEach(): Iterates over each element in an array and executes a provided callback function for each element.map(): Creates a new array by applying a provided function to each element of the original array.filter(): Creates a new array with all elements that pass a test provided by a function.reduce(): Executes a reducer function on each element of the array to reduce it to a single value.reduceRight(): Similar to reduce() but processes the array from right to left.some(): Tests whether at least one element in the array passes the provided test.every(): Tests whether all elements in the array pass the provided test.find(): Returns the first element in the array that satisfies the provided test.findIndex(): Returns the index of the first element in the array that satisfies the provided test.
We will cover these higher-order functions in detail in our dedicated article on Higher-Order Functions, where we'll explore callback functions, function composition, and advanced functional programming concepts.
2D & 3D Array
2D Array: A 2D array is an array of arrays. It is a collection of elements arranged in rows and columns, like a matrix.
// Defining a 2D array
let arr2D = [
[1, 2, 3], // First row
[4, 5, 6], // Second row
[7, 8, 9] // Third row
];
console.log(arr2D[0]); // Output: [1, 2, 3] (First row)
console.log(arr2D[1][2]); // Output: 6 (Element in second row, third column)
//Write program to find sum of all element in the given matrix.
// Loop through each row
for (let i = 0; i < arr2D.length; i++) {
// Loop through each element in the current row
for (let j = 0; j < arr2D[i].length; j++) {
sum += arr2D[i][j]; // Add the element to sum
}
}
console.log("Sum of all elements:", sum); // Output: 45
3D Array: A 3D array is an array of arrays of arrays. It can be thought of as a cube of elements arranged in three dimensions: length, width, and height.// Defining a 3D array
let arr3D = [
[ // First 2D array (layer 1)
[1, 2], // First row in first layer
[3, 4] // Second row in first layer
],
[ // Second 2D array (layer 2)
[5, 6], // First row in second layer
[7, 8] // Second row in second layer
]
];
console.log(arr3D[0]); // Output: [[1, 2], [3, 4]] (First 2D array, first layer)
console.log(arr3D[1][1][0]); // Output: 7 (Element in second layer, second row, first column)Key Takeaways
Arrays are a fundamental data structure in JavaScript that enable you to store and manipulate collections of values. Understanding how to create arrays and use their methods is key to becoming proficient in JavaScript.