An array in JavaScript is a data structure that can be used to store fixed or variable number of elements. JavaScript has multple built-in methods that can be used for unique functionalities.
const arr = [1, 2, 3]; // Creating an array using array literal
let second = arr[1]; // Output: 2, reading by index.
arr[0] = 2 // Writing at an index.
// We are empty an array or pruning the array
arr.length = 0;
arr.length = 1;
arr = [];
slice
: Returns a new Array containing the elements of the receiver whose indices are between (including) start and (excluding) end.//Syntax: slice(start?, end?)
['a', 'b', 'c', 'd'].slice(1, 3)
//Output: [ 'b', 'c' ]
> ['a', 'b'].slice() // shallow copy
//Output: [ 'a', 'b' ]
.slice()
supports negative indices. If an index is negative, it is added to the length of an Array to produce a usable index. Therefore, the following two invocations of .slice() are equivalent
const arr = ['a', 'b', 'c'];
arr.slice(-1)
//Output: [ 'c' ]
arr.slice(arr.length - 1)
//Output: [ 'c' ]
push
- Adds one or more elements to the end of an array and returns the new length of the array.unshift
- Adds one or more elements to the beginning of an array and returns the new length of the array.// Push method
let arr = [1, 2, 3];
let length = arr.push(4, 5);
console.log("Array ", arr); //Output: Array [ 1, 2, 3, 4, 5 ]
console.log("Length of the array "length); //Output: Length of the array 5
// unshift
let arr = [1, 2, 3]
let length = arr.unshift(0, 1);
console.log(arr); // Output: [ 0, 1, 1, 2, 3 ]
console.log(length); // Output: 5
//spreading
let arr = [1, 2, 3]
let arr2 = [4, 5];
console.log([...arr, ...arr2]) // Output: [ 1, 2, 3, 4, 5 ]
pop
- Removes the last element from an array and returns that element.shift
- Removes the first element from an array and returns that element.splice
- Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
- Incase end index is not mentioned in splice method, it takes length of the array by default, like in this case arrToBeRemoved.splice(2) similar to arrToBeRemoved.splice(2, 4)
splice
Modifies the original array by removing, replacing, or adding elements to it instead of creating a new one likeslice
.
// pop() method
let arrToBeRemoved = [1, 2, 3, 4, 5];
let length = arrToBeRemoved.pop()
console.log(arrToBeRemoved); // Output: [1, 2, 3, 4]
console.log(length); // Output: 5
// shift() method
let arrToBeRemoved = [1, 2, 3, 4, 5];
let length = arrToBeRemoved.shift()
console.log(arrToBeRemoved); // Output: [2, 3, 4, 5]
console.log(length); // Output: 1
// splice() method
let arrToBeRemoved = [1, 2, 3, 4, 5];
let spliced = arrToBeRemoved.splice(2); // Incase end index is not mentioned it takes length of the array by default, like in this case arrToBeRemoved.splice(2) similar to arrToBeRemoved.splice(2, 4)
console.log(arrToBeRemoved); // Output: [1, 2]
console.log(spliced); // Output: [ 3, 4, 5 ]
let arrToBeRemoved = [1, 2, 3, 4, 5];
let spliced = arrToBeRemoved.splice(1, 2)
console.log(arrToBeRemoved); // Output: [1, 4, 5]
console.log(spliced); // Output: [ 2, 3 ]
// spead operator
const arrToBeRemoved = [1, 2, 3, 4, 5];
const [,, ...arr2] = arrToBeRemoved;
console.log(arr2); // Output: [3, 4, 5]
Finding:
.find
: returns the first Array element for which its callback returns true, Otherwise, it returns undefined.
// example 1
let arr = [5, 12, 8, 13, 40];
let found = arr.find(element => element > 10);
console.log(found); // Output: 12
// example 2
const found = [{id: 1, name: 'Madhukar'}, {id: 2, name: 'abc'}].find(f=> f.id===1);
console.log(found) // {id: 1, name: 'Madhukar'}
.findLast
: Traverses an Array from end to start. Returns the value of the first element for which callback returns a truthy value. If there is no such element, it returns undefined.
[-1, 2, -3].findLast(x => x < 0)
//Output: -3
[1, 2, 3].findLast(x => x < 0)
//Output: undefined
.findIndex
: Returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1.
const arr = [5, 12, 8, 13, 40];
found = arr.findIndex(element => element > 10);
console.log(found);
//Output: 1
.findLastIndex
: Traverses an Array from end to start. Returns the index of the first element for which predicate returns a truthy value. If there is no such element, it returns -1.
[-1, 2, -3].findLastIndex(x => x < 0)
//Output: 2
[1, 2, 3].findLastIndex(x => x < 0)
//Output: -1
.includes
: Determines whether an array includes a certain value among its entries, returning true or false as appropriate.
//array.includes(valueToFind [, fromIndex]);
const arr = [5, 12, 8, 13, 40];
let found = arr.includes(8);
console.log(found); //Output: true
.indexOf
: Returns the first index at which a given element can be found in the array, or -1 if it is not present.
//array.indexOf(searchElement [, fromIndex]);
const arr = [5, 12, 8, 13, 40];
let index = arr.indexOf(8);
console.log(found); //Output: 2
.lastIndexOf
: Returns the index of the last element that is strictly equal to searchElement. Returns -1 if there is no such element. Starts searching at index fromIndex, visiting lower indices next.
//array.indexOf(searchElement [, fromIndex]);
const arr = [5, 8, 8, 13, 40];
let index = arr.lastIndexOf(8);
console.log(index); //Output: 2
Transforming:
.map
: Creates a new array populated with the results of calling a provided function on every element in the calling array.
const arr = [1, 2, 3];
arr.map(x => x * 3); //Output: [3, 6, 9]
.flatMap
: Take a function callback as a parameter that controls how an input Array is translated to an output Array.
['a', 'b', 'c'].flatMap(x => [x,x])
//Output: [ 'a', 'a', 'b', 'b', 'c', 'c' ]
['a', 'b', 'c'].flatMap(x => [x])
//Output: [ 'a', 'b', 'c' ]
> ['a', 'b', 'c'].flatMap(x => [])
//Output: []
.filter
: Creates a new array collecting all elements for which the callback returns a truthy value.
[-1, 2, 5, -7, 6].filter(x => x >= 0)
//Output: [ 2, 5, 6 ]
['a', 'b', 'c', 'd'].filter((_x,i) => (i%2)===0)
//Output: [ 'a', 'c' ]
Computing summaries of Arrays:
.every
: Returns true if predicate returns a truthy value for every element. Otherwise, it returns false. Stops traversing an Array if the predicate returns a falsy value.
[1, 2, 3].every(x => x > 0)
//Output: true
[1, -2, 3].every(x => x > 0)
//Output: false
.some
: Tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
[1, 2, 3].some(x => x < 0)
//Output: false
[1, -2, 3].some(x => x < 0)
//Output: true
.reduce
: Executes a reducer function on each element of the array, resulting in a single output value.
[1, 2, 3].reduce((accu, x) => accu + x, 0)
//Output: 6
[1, 2, 3].reduce((accu, x) => accu + String(x), '')
//Output: '123'
.reduceRight
: Similar to reduce(), but applies the function from right to left instead of left to right.
[1, 2, 3].reduceRight((accu, x) => accu + String(x), '')
///Output: '321'
Looping over Arrays:
.forEach
: Calls callback for each element.
A for-of loop is usually a better choice: it’s faster, supports break and can iterate over arbitrary iterables.
['a', 'b'].forEach((x, i) => console.log(x, i))
//Output:
// Output: a 0
// b 1
.copyWithIn
: Copies the elements whose indices range from (including) start to (excluding) end to indices starting with target. Overlapping is handled correctly.
// copyWithin(target, start, end=this.length)
['a', 'b', 'c', 'd'].copyWithin(0, 2, 4)
//Output: [ 'c', 'd', 'c', 'd' ]
.from
: The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.
const set = new Set(["foo", "bar", "baz", "foo"]);
Array.from(set);
//Output: [ "foo", "bar", "baz" ]
.spreading
: Creates a new instance of array.
[...[1,2], ...[3, 4]]
//Output: [1, 2, 3, 4]
.join
: Creates and returns a new string by concatenating all of the elements in an array, separated by commas or a specified separator string.
let arr = ['Hello', 'World'];
let str = arr.join(' ');
// Output: 'Hello Wor
.concat
: Returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.
let arr1 = [1, 2];
let arr2 = [3, 4];
let newArr = arr1.concat(arr2);
// Output: [1, 2, 3, 4]