Array in JavaScript
Array In JavaScript In details. Array methods, basics and destructuring.
What is array?
Array is reference type ordered collection of items. In JavaScript, an array is a special type of object used to store multiple values in a single variable. Arrays can hold any type of data, including numbers, strings, objects, or even other arrays. Each element in an array has an index, starting from 0.
let arr = [1, 2, 3, 4]
console.log(arr);
Array Indexing:
const array= [1,2,34,4,2,5,2,12,34,554,34,12,32,43,54,2]
console.log(array[0])
// For accessing the last element in the array we use array.length-1
console.log(array[array.length-1]);
Loops In Array:
For Loop in Array:
const numbers = [234,24,2,123,45,545,54,2,3]
for(let i=0; i<numbers.length; i++){
console.log(numbers[i]);
}
For of Loop in Array:
For of is specifically designed for iterating over the values of iterable objects like arrays.
const fruits = ['apple', 'mango','oranges','banana','strawberry']
for(let fruit of fruits){
console.log(fruit); // outputs: apple mango oranges banana strawberry
}
For in Loop Array:
For in is generally used for iterating over the properties (keys) of an object, but it can be used to iterate over the indices of an array
const fruits = ["apple", "mango", "oranges", "banana", "strawberry"];
for (let fruit in fruits) {
console.log(fruit); // outputs: 1, 2, 3, 4, 5
}
ES6 Array Features:
Array Destructing:
Array destructuring in JavaScript is a convenient way to extract values from an array and assign them to variables in a single statement. This feature simplifies extracting elements and assigning them directly to variables, making your code cleaner and more readable.
const fruits = ["apple", "mango", "oranges", "banana", "strawberry"];
const [a,b,c,d,e] = fruits
console.log(b,a,c,d,e);
Array spread Operator:
The spread operator (...
) in JavaScript allows you to expand elements of an array (or iterable) into individual elements. It's often used for copying, merging, or converting arrays, and offers great flexibility when working with arrays and objects.
const fruits = ["apple", "mango", "oranges", "banana", "strawberry"];
const ages = [12, 35, 38, 2, 37, 20, 36];
const fruits2 = [...fruits, ...ages] //->spread operator(...array_name)
fruits2[1]='chickoo'
console.log(fruits2);
Methods in Array:-
Push and Pop:
Push is used to insert an element at last index. Pop is used to delete an element at last index.
//Push
const arr = [1,2,3,4,5]
arr.push(6)
//Output:-
// [1,2,3,4,5,6]
//Pop
const arr = [1,2,3,4,5]
arr.push()
Shift and Unshift:
Shift is used to an element in first index. unshift is used to add element in the first index.
const arr = [1,2,3,4,5]
arr.shift()
//Output:-
// [2,3,4,5,6]
const arr = [1,2,3,4,5]
arr.unshift(9)
//Output:-
// [9,2,3,4,5,6]
Slice()
Returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included). Usage: To create a sub-array without modifying the original array.
let arr = [1, 2, 3, 4];
let subArr = arr.slice(1,3);
console.log(subArr); // subArr is [2, 3], arr is still [1, 2, 3, 4]
Concat():
Merges two or more arrays. This method does not change the existing arrays, but instead returns a new array. Usage: To combine multiple arrays.
const teamA = ['Alice', 'Bob'];
const teamB = ['Charlie', 'Dave'];
const allEmployees = teamA.concat(teamB);
//allEmployees: ['Alice', 'Bob', 'Charlie', 'Dave']
Sort():
Sorts the elements of an array in place and returns the sorted array. The default sort order is according to string Unicode code points. Usage: To sort elements.
let arr = [3, 1, 4, 2];
arr.sort(); // arr is now [1, 2, 3, 4]
console.log(arr);
Reserve():
Reverses the array in place. The first array element becomes the last, and the last array element becomes the first. Usage: To reverse the order of elements.
let arr3 = [1, 2, 3];
arr3.reverse(); // arr is now [3, 2, 1]
Join():
The join() method of Array instances creates and returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string.
const items = ['apple', 'banana', 'cherry'];
const arr3 = [1, 2, 3];
const itemList = arr3.join(' ');
console.log(itemList);
// itemList: 'apple, banana, cherry'
IndexOf():
The indexOf() method searches an array for an element value and returns its position.
const products = ['Laptop', 'Phone', 'Tablet'];
const index = products.indexOf('Tablet');
console.log(index);
// index: 1
ForEach():
In JavaScript, the method is used to iterate over the elements of an array. It executes a provided function once for each array element and is typically used when you want to perform an action on each item in the array without returning a new array.
let arr = [3, 1, 4, 2];
arr.forEach(num => console.log(num*2)) // 6, 2, 8, 4
Map():
In JavaScript, the map()
function is used to create a new array by applying a function to every element in the original array. Unlike forEach()
, which is primarily used for side effects, map()
is used when you want to transform the array and get a new array with the transformed values.
currentValue
: The current element being processed.index
(optional): The index of the current element.array
(optional): The original arraymap()
was called on.
The map()
method always returns a new array with the same number of elements as the original array, where each element is the result of the transformation applied in the callback.
const ages = [24, 21, 24, 21];
const newAges = ages.map(age => age + 1) //-> Implicit Return
const newAges = ages.map((age) => { //-> Explicit return
return age + 1;
});
console.log(newAges);
Filter():
In JavaScript, the filter()
method creates a new array with all elements that pass the test implemented by the provided function. It's used to filter out elements from an array based on a condition, returning only the elements that satisfy that condition.
let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter((number) => number % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]
Reduce():
In JavaScript, the reduce()
method is used to iterate through an array and accumulate a single output value based on a callback function. Itβs particularly useful for calculating sums, products, or transforming arrays into objects or other forms of data.
accumulator
: The running total or accumulated result of the function.currentValue
: The current element being processed.index
(optional): The index of the current element.array
(optional): The original array.
initialValue
: The initial value for the accumulator (optional but recommended).
let numbers = [11, 22, 33, 44, 55];
let sum = numbers.reduce(function (accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // 165
Interview questions
What is map()?
What is filter()?
What is reduce()?
What is polyfill map()?
What is polyfill filter()?
map() Vs forEach()?
Chaining map, filter and reduce?