JavaScript Arrays
Creating Arrays
There are several ways to create arrays in JavaScript:
1. Using Square Brackets
The simplest and most common way to create an array is by using square brackets [].
let fruits = [‘Apple’, ‘Banana’, ‘Cherry’];
2. Using the Array Constructor
You can also create an array using the Array constructor.
let fruits = new Array(‘Apple’, ‘Banana’, ‘Cherry’);
Accessing Array Elements
Array elements are accessed using their index, which starts from 0.
let fruits = [‘Apple’, ‘Banana’, ‘Cherry’];
console.log(fruits[0]); // Output: Apple
console.log(fruits[1]); // Output: Banana
console.log(fruits[2]); // Output: Cherry
Modifying Array Elements
You can modify an array element by assigning a new value to a specific index.
let fruits = [‘Apple’, ‘Banana’, ‘Cherry’];
fruits[1] = ‘Blueberry’;
console.log(fruits); // Output: [‘Apple’, ‘Blueberry’, ‘Cherry’]
Array Properties and Methods
1. Length: The length property returns the number of elements in an array.
let fruits = [‘Apple’, ‘Banana’, ‘Cherry’];
console.log(fruits.length); // Output: 3
2. toString(): The toString method for arrays converts the array elements into a single string, separated by commas.
let fruits = [‘Apple’, ‘Banana’, ‘Cherry’];
let fruitsString = fruits.toString();
console.log(fruitsString); // Output: “Apple,Banana,Cherry”
3. Push and Pop: The push method adds one or more elements to the end of an array, and the pop method removes the last element from an array.
let fruits = [‘Apple’, ‘Banana’];
fruits.push(‘Cherry’);
console.log(fruits); // Output: [‘Apple’, ‘Banana’, ‘Cherry’]
let lastFruit = fruits.pop();
console.log(lastFruit); // Output: Cherry
console.log(fruits); // Output: [‘Apple’, ‘Banana’]
4. Shift and Unshift: The shift method removes the first element from an array, and the unshift method adds one or more elements to the beginning of an array.
let fruits = [‘Apple’, ‘Banana’, ‘Cherry’];
let firstFruit = fruits.shift();
console.log(firstFruit); // Output: Apple
console.log(fruits); // Output: [‘Banana’, ‘Cherry’]
fruits.unshift(‘Strawberry’);
console.log(fruits); // Output: [‘Strawberry’, ‘Banana’, ‘Cherry’]
5. Splice: The splice method adds/removes elements from an array.
let fruits = [‘Apple’, ‘Banana’, ‘Cherry’];
fruits.splice(1, 1, ‘Blueberry’, ‘Kiwi’); // Removes 1 element at index 1 and adds 2 new elements
console.log(fruits); // Output: [‘Apple’, ‘Blueberry’, ‘Kiwi’, ‘Cherry’]
The first parameter (1) defines the position where new elements should be added (spliced in).
The second parameter (1) defines how many elements should be removed.
The rest of the parameters (“Blueberry ” , “Kiwi”) define the new elements to be added.
6. Slice: The slice method returns a new array containing a portion of an array.
let fruits = [“apple”, “banana”, “cherry”, “date”, “elderberry”];
let slicedFruits = fruits.slice(1, 3);
// Extract a portion of the array from index 1 to 3 (not including index 3)
console.log(slicedFruits); // Output: [“banana”, “cherry”]
console.log(fruits);
// Original array remains unchanged: [“apple”, “banana”, “cherry”, “date”, “elderberry”]
The slice() method can take two arguments like slice(1, 3).
The method then selects elements from the start argument, and up to (but not including) the end argument.
If the end argument is omitted the slice() method slices out the rest of the array.
7. Concat: The concat method merges two or more arrays into a new array.
let fruits = [‘Apple’, ‘Banana’];
let moreFruits = [‘Cherry’, ‘Date’];
let allFruits = fruits.concat(moreFruits);
console.log(allFruits); // Output: [‘Apple’, ‘Banana’, ‘Cherry’, ‘Date’]
8. Join: The join method joins all elements of an array into a string.
let fruits = [‘Apple’, ‘Banana’, ‘Cherry’];
let fruitString = fruits.join(‘, ‘);
console.log(fruitString); // Output: Apple, Banana, Cherry
9. ForEach: The forEach method executes a provided function once for each array element.
let fruits = [‘Apple’, ‘Banana’, ‘Cherry’];
fruits.forEach(function(fruit) {
console.log(fruit);
});
// Output:
Apple
Banana
Cherry
10. Map: The map method creates a new array with the results of calling a provided function on every element in the calling array.
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled);// Output: [2, 4, 6, 8]
11. Filter: The filter method creates a new array with all elements that pass the test implemented by the provided function.
let numbers = [1, 2, 3, 4];
let even = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(even); // Output: [2, 4]
12. at Method: Returns the element at a specified index.
const array = [10, 20, 30, 40];
console.log(array.at(2)); // Output: 30
console.log(array.at(-1)); // Output: 40 (last element)
13. delete Method: Removes an element from the array by index (not a method but shown for reference).
const array = [10, 20, 30, 40];
delete array[2];
console.log(array); // Output: [10, 20, empty, 40]
14. copyWithin Method: Copies part of an array to another location within the same array without changing its length.
const array = [10, 20, 30, 40, 50];
array.copyWithin(0, 3, 5); // Copies elements at index 3 to 5 to index 0
console.log(array); // Output: [40, 50, 30, 40, 50]
15. flat Method: Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
const array = [1, [2, [3, [4, 5]]]];
const newArray = array.flat(2); // Flattens the array up to depth 2
console.log(newArray); // Output: [1, 2, 3, [4, 5]]
16. indexOf Method: Returns the first index at which a given element can be found in the array, or -1 if it is not present.
const array = [2, 9, 9, 4];
console.log(array.indexOf(9)); // Output: 1
console.log(array.indexOf(7)); // Output: -1
17. lastIndexOf Method: Returns the last index at which a given element can be found in the array, or -1 if it is not present.
const array = [2, 9, 9, 4];
console.log(array.lastIndexOf(9)); // Output: 2
console.log(array.lastIndexOf(7)); // Output: -1
18. includes Method: Determines whether an array includes a certain value among its entries, returning true or false.
const array = [1, 2, 3];
console.log(array.includes(2)); // Output: true
console.log(array.includes(4)); // Output: false
19. find Method: Returns the first element in the array that satisfies the provided testing function. Otherwise, it returns undefined.
const array = [5, 12, 8, 130, 44];
const found = array.find(element => element > 10);
console.log(found); // Output: 12
20. findIndex Method: Returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1.
const array = [5, 12, 8, 130, 44];
const index = array.findIndex(element => element > 10);
console.log(index); // Output: 1
21. findLast Method: Starts from the end of an array and returns the value of the first element that satisfies a condition.
const array = [5, 12, 8, 130, 44];
const found = array.findLast(element => element > 10);
console.log(found); // Output: 44
22. findLastIndex Method: Returns the index of the last element that satisfies a condition.
const array = [5, 12, 8, 130, 44];
const index = array.findLastIndex(element => element > 10);
console.log(index); // Output: 4
23. sort Method: Sorts the elements of an array of strings in place and returns the sorted array. The sort is based on string Unicode code points.
const fruits = [‘banana’, ‘apple’, ‘orange’, ‘mango’];
fruits.sort();
console.log(fruits); // Output: [‘apple’, ‘banana’, ‘mango’, ‘orange’]
24. reverse Method: Reverses the elements of an array of strings in place and returns the reversed array.
const fruits = [‘banana’, ‘apple’, ‘orange’, ‘mango’];
fruits.reverse();
console.log(fruits); // Output: [‘mango’, ‘orange’, ‘apple’, ‘banana’]
25. toSorted Method: Returns a new array with the elements sorted, leaving the original array unchanged.
const fruits = [‘banana’, ‘apple’, ‘orange’, ‘mango’];
const sortedFruits = fruits.toSorted();
console.log(sortedFruits); // Output: [‘apple’, ‘banana’, ‘mango’, ‘orange’]
console.log(fruits); // Output: [‘banana’, ‘apple’, ‘orange’, ‘mango’] (original array unchanged)
26. toReversed Method: Returns a new array with the elements reversed, leaving the original array unchanged.
const fruits = [‘banana’, ‘apple’, ‘orange’, ‘mango’];
const reversedFruits = fruits.toReversed();
console.log(reversedFruits); // Output: [‘mango’, ‘orange’, ‘apple’, ‘banana’]
console.log(fruits); // Output: [‘banana’, ‘apple’, ‘orange’, ‘mango’] (original array unchanged)