Javascript array operations
In this article, we will outline 16 most commonly used javascript array operations using array methods, which include adding and removing elements, sorting the array, finding index of elements, filtering, merging and looping arrays with examples.
push()
method adds an element to the array. The element is always added to the end, that is, the added element will be the last array element.push()
modifies the original array and returns its new length. Example,
let numbers = [1, 2, 3]; numbers.push(6); console.log(numbers); // [1, 2, 3, 6]
2. Remove elements: pop()
pop()
method removes an element from the array. The removed element is always the last array element.
pop()
modifies the original array and returns the removed element. Example,
let numbers = [1, 2, 3]; let last = numbers.pop(); console.log(numbers); // [1, 2] console.log(last); // 3
3. Add elements: unshift()
unshift()
method adds an element to the array. The element is always added to the start, that is, the added element will become the first array element.
Thus, unshift()
is similar and opposite to push()
. Similar in that it adds an element and opposite in that, it adds the element at the beginning while push()
adds the element at the end.
unshift()
modifies the original array and returns its new length. Example,
let numbers = [1, 2, 3]; numbers.unshift(0); console.log(numbers); // [0, 1, 2, 3]
4. Remove elements: shift()
shift()
method removes an element from the array. The removed element is always the first array element.
Thus, shift()
is similar and opposite to pop()
.
Similar in that it removes an element and opposite in that, it removes the first element while pop()
removes the last element.
shift()
also modifies the original array and returns the removed element. Example,
let numbers = [1, 2, 3]; let first = numbers.shift(); console.log(numbers); // [2, 3] console.log(first); // 1
slice() function is used to extract a portion of array between the provided indexes.
It accepts two numeric arguments representing the indexes of array elements and returns a new array with elements between those two argument indexes.
Indexes start from 0. Elements in the resulting array are between start and (end -1) indexes.
slice()
returns a shallow copy of a portion of the array, which means that the original array is not modified. Example,
let numbers = [1, 2, 3, 4, 5]; // get array between indexes 1 and 4 let sliced = numbers.slice(1, 4); console.log(sliced); // [2, 3, 4]
6. Replace elements: splice()
This method is used to remove or replace elements from the array.
It takes three arguments: the start index, the number of elements to remove, and the elements to add.
Out of these, only the first argument is mandatory.
If only first argument is provided, splice()
removes all the elements starting from that index.
splice()
method modifies the original array. Example,
let letters = ['A', 'B', 'C', 'D', 'E']; // replace two elements starting index 2 letters.splice(2, 2, 'X', 'Y'); console.log(letters); // ['A', 'B', 'X', 'Y', 'E'] letters = ['A', 'B', 'C', 'D', 'E']; // remove 2 elements starting index 2 letters.splice(2, 2); console.log(letters); // ['A', 'B', 'E'] letters = ['A', 'B', 'C', 'D', 'E']; // remove 3 elements starting index 2 letters.splice(2, 3); console.log(letters); // ['A', 'B'] letters = ['A', 'B', 'C', 'D', 'E']; // replace 3 elements starting index 2 letters.splice(2, 3, 'X', 'Y', 'Z'); console.log(letters); // ['A', 'B', 'X', 'Y', 'Z'] letters = ['A', 'B', 'C', 'D', 'E']; // replace all elements starting index 3 letters.splice(3); console.log(letters); // ['A', 'B','C']
7. Sorting array: sort()
As the name states, it sorts the array in-place. In-place means that no new array is created and the original array is modified.
By default, sort()
sorts the array in ascending order. Example,
let numbers = [3, 1, 4, 2]; numbers.sort(); console.log(numbers); // [1, 2, 3, 4]
You can also supply a function to sort()
. This function defines the sort order and it must return either 0, -1 or 1.
This function can also be an arrow function.
Below is an example to sort an array of objects based on id field
const employees = [ { name: "A", id: 11 }, { name: "X", id: 27 }, { name: "B", id: 35 }, { name: "W", id: 12 }, { name: "C", id: 3 }, { name: "T", id: 27 }, ]; // sort by id items.sort((a, b) => a.id- b.id);
8. Searching element: indexOf()
This method returns the first index at which a given element can be found in the array, or -1 if it is not present.
indexOf()
method takes a single argument, which is the element to search for. Example,
let numbers = [1, 2, 3, 4]; let index = numbers.indexOf(2); console.log(index); // 1 index = numbers.indexOf(10); console.log(index); // -1
Returns the last index at which a given element can be found in the array, or -1 if it is not present. Example,
let numbers = [1, 3, 3, 4, 2]; let index = numbers.lastIndexOf(3); console.log(index); // 2
10. Reversing array: reverse()
Reverses the order of elements of the array. This means that the last element becomes the first, second last element becomes the second and so on.
Original array is modified. Example,
let letters = ['W', 'X', 'Y', 'Z']; letters.reverse(); console.log(letters); // ['Z', 'Y', 'X', 'W']
11. Transforming array: map()
map() function is used to apply some operation on elements of the array or to transform array elements. This is the reason it is called map.
map()
accepts a callback function, which is called for each array element.
It accepts the array element as argument and returns a value. It is up to the implementor how this element needs to be transformed.
Below example maps each element of an array to its square
let numbers = [1, 2, 3, 4]; let square = numbers.map(x => x * x); console.log(square); // [2, 4, 9, 16]
12. Filtering Arrays: filter()
Javascript filter() function is applied to arrays and is used to get an array of only those elements which satisfy a particular requirement or condition.
filter()
accepts a callback function as argument, which is called for each array element.
If the callback function returns true as per the implemented condition, then this element is added to the result array, otherwise not.
filter()
does not modify the array on which it is called but creates and returns a new array having only those elements which fulfill the filter condition.
Rest elements are removed or filtered out from the result array. Example,
// callback function for filter function compare(element) { // compare element with 5 return element < 5; } // declare array let numbers = [2,4,5,1,20]; let filtered = numbers.filter(compare); console.log(filtered); // [2,4,1]
You can also pass an arrow function to filter()
as shown below
// declare array let numbers = [2,4,5,1,20]; // get array elements lesser than 5 let filtered = numbers.filter(number => number < 5); console.log(filtered ); // 2,4,1
13. Accumulating array: reduce()
reduce()
function used for reducing an array into a single value.
reduce()
accepts a callback function as argument, which is invoked for each element of the array and accumulates the result. The reducer function takes two arguments: the accumulated value and the current value.
Below is an example to calculate the sum of array of integers using reduce()
let numbers = [23, 12, 9, -2]; let sum = numbers.reduce(function(accumulator, currentValue) { return accumulator + currentValue; }, 0); console.log(sum); // 42
When the callback function is called for the first time, there is no return value.
A default initial value can be supplied as the second argument for this(first time), such as 0 in above example.
If not supplied, the first array element is used as the initial value and iteration starts from the next element.
Argument function of reduce()
can also be an arrow function as shown below.
let numbers = [23, 12, 9, -2]; let sum = numbers.reduce( (accumulator, currentValue) => accumulator + currentValue); console.log(sum); // 42
Concats or merges two or more arrays.
It returns a new array containing all the elements from all the arrays.
If the arrays contain duplicate elements, then the result array also contains all those elements. Example,
let n1=[1,2,3]; let n2=[2,3,4]; let n3=n1.concat(n2); console.log(n3); // [1, 2, 3, 2, 3, 4]
15. Array to string: join()
join()
function combines all elements of an array into a string.
It accepts an optional argument, which if provided, becomes the separator between the elements. Example,
const letters= ['A','B','C']; console.log(letters.join()); // "A,B,C" console.log(letters.join('')); // "ABC" console.log(letters.join('-')); // "A-B-C"
16. Array Iteration: forEach()
This method calls a function for each element in the array.
forEach()
method takes a single argument: a callback function to be executed for each element. Example,
let letters = ['A', 'B', 'C', 'D']; letters.forEach(l => console.log(l.toLowerCase())); // Result: // a // b // c // d
That is all on different array operations in javascript. Hope the article was useful.