Javascript: All About Array and Its Method
This article is about arrays in Javascript.
1. What is an array?
An array is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable. Arrays are generally described as "List-type objects". They are a single type of object that contains multiple types of values stored in it like a list object. We store array objects into some variables and get that value by using a variable whenever it is required. We can access arrays of objects by multiple iterations in such a way that we access each value of the array individually.
2. Creating an array:
We create an array by using a square bracket '[ item1,item2,item3 ...so on]', and all the items are placed inside the square bracket, and item1, item2, and item3 are its elements.
let country = ['India', 'USA', 'Japan', 'China'];
console.log(country); // ['India', 'USA', 'Japan', 'China']
Here, India, USA, Japan, and China is an element in the Array.
3. Finding The Length of an Array:
We can find the length of the array i.e.(How many elements are there in the array) by using the length function.
let country = ['India', 'USA', 'Japan', 'China'];
console.log(country.length); // 4
4. How to Access and Modify Array Items:
Items in an array are placed in number sequencing by using an index starting from '0' to it will go up to 'n' number of indexing position. So in order to access the first item, we use index 0, to access the second we use index 1, and so on. We can access individual items in the array using a bracket sign and put the item's index.
let fruits = ['Apple', 'Banana', 'Carrot', 'DragonFruit'];
console.log(fruits[0]); // Apple
We can also modify an item in an array by giving a single array item a new value.
let fruits = ['Apple', 'Banana', 'Carrot', 'DragonFruit'];
fruits[0] = 'Grape';
console.log(fruits); // ['Grape', 'Banana', 'Carrot', 'DragonFruit']
5. Finding Items in An Array:
Finding an Item inside an array is easy if we know the index of that item. But if we don't know the index we can find the index of a particular item using the indexOf() method.This takes an item as an argument and returns the index, or -1 if the item was not found in the array:
const fruits = ['Grape', 'Banana', 'Carrot', 'DragonFruit'];
console.log(fruits.indexOf('Carrot')); // 2
console.log(fruits.indexOf('Apple')); // -1
6. Adding an element in an Array:
To add one or more items to the end of an array we can use push(). Note that we need to include one or more items that we want to add to the end of your array.The element will be added to the last index position of the array.
const cities = ['Mumbai', 'Delhi']
cities.push('Bangalore');
console.log(cities); // ['Mumbai', 'Delhi', 'Bangalore']
cities.push('Hyderabad', 'Kolkata');
console.log(cities); // ['Mumbai', 'Delhi', 'Bangalore', 'Hyderabad', 'Kolkata']
If we want to add an element at the first position or starting position of the array we use unshift().
7. Removing an element in an Array:
To remove the last item from the array, use pop(). Note that we need to include one or more items that we want to remove from the end of your array. The element will be removed from the last index position of the array.
const cities = ['Mumbai', 'Delhi'];
cities.pop();
console.log(cities); //Mumbai
If we want to remove an element from the first position or starting position of the array we use shift().
8. Accessing Every Item in an array:
If we will want to access every item in the array. we can do this by using the for...of statement:
const fruits = ['Grape', 'Banana', 'Carrot', 'DragonFruit'];
for (const fruit of fruits ) {
console.log(fruit); // Grape, Banana, Carrot, DragonFruit
}
Different Method Used In Array:
Map():
This method creates a new array resulting in to call of a provided function on every element in this array. Map objects are collections of key-value pairs. A key in the Map may only occur once, it is unique in the Map's collection in the case of 2 elements.
const numbers = [1, 4, 9];
const roots = numbers.map((num) => Math.sqrt(num));
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
Filter():
This method creates a new array with only elements that fulfill the condition inside the provided function. filter() method creates a shallow copy of a portion of a given array, filtered down to the elements from the given array that fulfill the test implemented by the provided function.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Sort():
This method is used to sort the items in an array’s elements in ascending or descending order.
const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.sort((a, b) => a - b);
// numbers and sorted are both [1, 1, 3, 4, 5]
sorted[0] = 10;
console.log(numbers[0]); // 10
Foreach():
The forEach() method executes a provided function once for each array element.
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"
Concat:
The concat() method is used to merge two or more arrays. This method does not change the existing arrays. But it returns a new array.
const letters = ['a', 'b', 'c'];
const numbers = [1, 2, 3];
const alphaNumeric = letters.concat(numbers);
console.log(alphaNumeric);
// results in ['a', 'b', 'c', 1, 2, 3]
Every():
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));// true
Some():
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true. Otherwise, it returns false. It doesn't modify the array.
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
Includes():
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
const arr = ['a', 'b', 'c'];
arr.includes('c', 2) // true
arr.includes('c', 3) // false
Join():
The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
const a = ['Wind', 'Water', 'Fire'];
a.join(); // 'Wind,Water,Fire'
a.join(', '); // 'Wind, Water, Fire'
a.join(' + '); // 'Wind + Water + Fire'
a.join(''); // 'WindWaterFire'
Reduce():
The reduce() method executes a reducer function for the array element. This method returns a single value of the function's accumulated result. The reduce() method does not execute the function for empty array elements and it does not change the original array.
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(previousValue, currentValue) => previousValue + currentValue,
initialValue
);
console.log(sumWithInitial);
// expected output: 10
Find():
The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
const ages = [3, 10, 18, 20];
function checkAge(age) {
return age > 18;
}
console.log(ages.find(checkAge)); //20
FindIndex():
The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// expected output: 3
IndexOf():
The 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 fruits = ["Banana", "Orange", "Apple", "Mango"];
let index = fruits.indexOf("Apple"); //2
Fill():
The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the new array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.fill("Kiwi")); //['Kiwi', 'Kiwi', 'Kiwi', 'Kiwi']
Reverse():
The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.
const items = [1, 2, 3];
console.log(items); // [1, 2, 3]
items.reverse();
console.log(items); // [3, 2, 1]
Splice():
The splice() method adds and/or removes array elements. The splice() method overwrites the original array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// At position 2, we add 2 elements:
fruits.splice(2, 0, "Lemon", "Kiwi");
consoe.log(fruits); // Banana,Orange,Lemon,Kiwi,Apple,Mango
Slice():
The slice() method returns selected elements in an array, as a new array. This method selects from a given start, up to an (n position) given end. It does not change the original array.
const fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
const citrus = fruits.slice(1, 3);
// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
At():
The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.
const fruits = ['Apples', 'Apricots', 'Avocados', 'Bananas', 'Boysenberries', 'Blueberries', 'Bing Cherry'];
fruits.at(0); //Apples
fruits.at(-1); //Bing Cherry
fruits.at(-2); //Blueberries
Shift():
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1
Unshift():
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon", "Pineapple");
console.log(fruits); // Lemon,Pineapple,Banana,Orange,Apple,Mango
This is the end of the blog I hope you all learn something about Array in Javascript. If you like this blog then please give a thumbs up. And I will see you in the next blogs.