JavaScript Array Methods

Pirakavi Santhiran
2 min readFeb 4, 2021

--

Arrays are a good way to store different elements in a single variable.

The first index in the array is 0.

Declaration of an Array

var arr1 = [];
var arr2 = new array();

Get the length of an array

var arr1 = [1,2,3,4,5];
arr1.length //returns 5

Merge two arrays

Method 1 (Concat)

const arr1= ['one', 'two'];
const arr2= ['ten', 'twenty'];

const combined1 = [].concat(arr1, arr2); // [ 'one', 'two', 'ten', 'twenty' ]
const combined2 = arr1.concat(arr2); // [ 'one', 'two', 'ten', 'twenty' ]

Method 2 (Spread)

const arr1= ['one', 'two'];
const arr2= ['ten', 'twenty'];

const combined2= [...arr1, ...arr2]; // [ 'one', 'two', 'ten', 'twenty' ]

Difference between Spread vs Concat

Let’s think you have an array with numbers and you want to add a string into that array. which way you want to choose!

SPREAD or CONCAT

Let’s try an example

const arr1 = [1, 2];
const str = 'Birthday'
const result = [...arr1, ...str]

what is the output for above example!

1,2,B,i,r,t,h,d,a,y

Is this output you want!
No, Right!

so in this case, Concat will help us!

const arr1 = [1, 2];
const str = 'Birthday'
const result = [].concat(arr1, str) // 1,2,Birthday

woah! you got your expected output!

Adding items to an array

const arr1 = [1, 2];arr1.push('Birthday')document.write(arr1); //1,2,Birthday

see you have added item into end of an array, something you want to add beginning of an array?
yes , you can use “unshift”

const arr1 = [1, 2];arr1.unshift('Birthday')document.write(arr1); //Birthday,1,2

Remove items from array

const arr1 = [1, 2, 3, 4];
const arr2 = arr1.shift();
document.write(arr1); //2,3,4
document.write(arr2); //1

you can remove items from end also,

const arr1 = [1, 2, 3, 4];
const arr2 = arr1.pop();
document.write(arr1); //1,2,3
document.write(arr2); //4

do you know about Slice() method,

arr.slice([begin[, end]])

let’s look at an example

var arr = ['one', 'two', 'three', 'four', 'five', 'six'];
document.write(arr .slice(2)); //three,four,five,six
document.write(arr .slice(2,4)); //three,four
document.write(arr .slice(1,5)); //two,three,four,five

slice method is used to get a portion of an array (Begin index included , End index not included).

Conclusion

I hope you all get some knowledge about JavaScript Arrays

Thank you so much for reading!

References : https://www.samanthaming.com/tidbits/49-2-ways-to-merge-arrays/

--

--

Pirakavi Santhiran

The beautiful thing about learning is that nobody can take it away from you