Array methods in Javascript

ยท

6 min read

Functional programming is very handy while building applications as it provides several inbuilt array methods. However, in this blog, we are going to look at some popular methods in an array that we should use on regular basis.

Array.join()

๐—”๐—ฟ๐—ฟ๐—ฎ๐˜†.๐—ท๐—ผ๐—ถ๐—ป(): The join() method creates and returns a new string by concatenating all of the elements in an array. By default, elements will be separated by commas.

const country = ["India", "America", "Canada"];
const result = country.join();
console.log(result);           //   "India,America,Canada"

But if we want to return a string by concatenating an array element separated by any other character, we can achieve this by passing a character in join() as an argument.

const country = ["India", "America", "Canada"];
const result = country.join('+');
console.log(result);           //   "India+America+Canada"

Array.push():

This method is used when we want to add any element at the end of an array.

const pets = ["Cat", "Dog", "Cow"];
pets.push('Goat');
console.log(pet);           //   ["Cat", "pet","Cow", Goat"]

The push() method add an element at the end and return the length of a modified array.

const pets = ["Cat", "Dog", "Cow"];
const  length = pets.push('Goat');
console.log(length);           //   4

Array.pop()

Array.pop() method is used to remove the last element of an array. It returns the removed element of the array.

const pets = ["Cat", "Dog", "Cow"];
const ans = pets.pop()
console.log(pets);           //    ["Cat", "Dog"]
console.log(ans);            //     "Cow"

Array.shift()

If we want to remove an element from the beginning of an array, then the shift() method can be used to achieve this. The shift () method returns the removed element.

const pets = ["Cat", "Dog", "Cow"];
const ans = pets.shift()
console.log(pets);           //    ["Dog", "Cow"]
console.log(ans);            //     "Cat"

Array.unshift()

This method is used when we want to add one or more than one elements at the beginning of an array.

const numbers = [1,2,3,4,5];
numbers.unshift(0);
console.log(numbers);    // [0,1,2,3,4,5]
numbers.unshift(6,7);
console.log(numbers);    // [6,7,1,2,3,4,5]

##Array.concat()

concat() method is used when we want to concatenate two arrays. This method doesn't modify the given array but it returns a new array by concatenating both arrays.

Let's understand by example

const myFriends = ["Jack", "Doe"];
const yourFriends = ["Marry", "Salena"];
const ourFriends = myFriends.concat(yourFriends);
console.log(ourFriends)        // ["Jack","Doe","Marry","Salena"]

Array.slice()

The slice() method returns a new array consisting of a portion of the array selected from start to end (excluding end) and does not modify the original array.

const alphabets= ['a', 'b', 'c', 'd', 'e', 'f'];

//if end not specified, the array will be sliced until the end of the array
const sliced1 = alphabets.slice(3);
console.log(sliced1);  // ['d', 'e', 'f']

//here we slice the array from index 0 to 2
const sliced2 = alphabets.slice(0,2);
console.log(sliced2);  // ['a', 'b',]

//if we specify the end greater or equal to array length, it will get sliced upto the end of an array
const sliced3 = alphabets.slice(2,8);
console.log(sliced3);  // ['c', 'd', 'e', 'f'];

//we can also specify negative start or end index, (-1) refers to last element of an array
const sliced3 = alphabets.slice(2,-1);
console.log(sliced3);  // ['c', 'd', 'e'];


const sliced4 = alphabets.slice(-3);
console.log(sliced4);  // ['d', 'e', 'f'];

Array.splice()

The splice() method adds and/or removes array element and modify the original array.

const socials = ["Instagram", "Twitter", "Facebook"];
socials.splice(1, 0, "LinkedIn");
console.log(socials);   // ["Instagram", "LinkedIn", "Twitter", "Facebook"]

Array.forEach()

The forEach() method on the array executes a provided function once for each array element.

 const array = [1,2,3];
array.forEach((number) => console.log(number * 2))

// output
2 4 6

Array.map()

The map() method is used to traverse the given array and return a new array which will be the result of the provided function(as an argument in the map() method) executed on each element

const numbers = [1,2,3,4,5,6];
const result = numbers.map((num) => num*2);
console.log(result);             //  [2,4,6,8,10,12]

Array.filter()

filter() method returns a new array consisting of the only element which satisfied the condition provided by an argument inside the filter() method.

const numbers = [1,2,3,4,5,6];
const result = numbers.filter((num) => num%2 == 0);
console.log(result);             //  [2,4,6]

Array.reduce()

Reduce() method in javascript is used to reduce the array to a single value.

Syntax: arr.reduce(callback(accumulator, currentValue), initialValue);

let numbers = [1,2,3];

let sum =  numbers.reduce(function(total, number){
  return total + number
}, 0);

console.log(sum );     //  6

Array.indexOf()

Indexof() method is used to find the index of the first occurrence of an element in an array.

const numbers = [1,4,2,5,3,4,1,5,4];
const index = numbers.indexOf(4);
console.log(index)     // 1

But suppose we want to find the first occurrence after ignoring the first n index. Then we can pass another argument as an index in indexOf(). Now, the search will start after skipping the first n element.

const numbers = [1,2,4,5,3,4,1,5,4];
const index = numbers.find(4, 3);
console.log(index);     //5

Array.lastindexof()

lastIndexOf() method is used to find the last index at which a given element is present. If the given element is not found in an array, -1 will be returned.

const numbers = [2, 5, 9, 2];
numbers.lastIndexOf(2);     // 3
numbers.lastIndexOf(7);     // -1

Array.findIndex()

We have already seen above how to find the index of a given element in an array. But what if we want to find the index of that element that satisfy our condition? Here, the use of the findIndex() method comes into the picture.

const ages = [3, 10, 18, 20];

function checkAge(age) {
  return age > 18;
}

ages.findIndex(checkAge);

Array.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 modified array.

Syntax: array.fill(value, start, end)

const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

Array.find()

find() method is very much similar to findIndex() method which we have discussed above. The only difference between both of them is find() method returns the element itself whereas findIndex() returns the index value.

const ages = [3, 10, 18, 20];
const result = ages.find((age) => age > 12);
console.log(result);    // 18

Array.includes()

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Banana");    // true

Array.some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false.

const arr1 = [1,3,5,7,8];
const arr2 =[2,4,5,7,9,11]

arr1.some((num) => num > 10);  // output : false
arr2.some((num) => num > 10); // output: true

Array.every()

Array.every() method tests whether all elements in the array pass the test implemented by the provided function.

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true

Array.flat()

The flat() method creates a new array by flattening a nested array up to the specified depth.

The flat() method takes a single parameter, an integer specifying how deep a nested array should be flattened. Its default value is 1.

let arr = [1,2,3,[4,5,6,[7,8,9]]];
console.log(arr.flat()); // [1,2,3,4,5,6,[7,8,9]];
console.log(arr.flat(2)); // [1,2,3,4,5,6,7,8,9];

Conclusion

I hope you enjoyed this article on array methods. Now, youโ€™ll be able to perform operations using array methods. If you liked it, you are more than welcome to make some comments below or leave a like :)

Did you find this article valuable?

Support Md Talha by becoming a sponsor. Any amount is appreciated!

ย