Learn about some useful methods in Javascript Arrays

In this tutorial we will explore some methods which will help you to do certain operations on Javascript Arrays.

The code for this lecture is available on Github

Consider this string

let fruits = 'Mango, Peach, Banana';

What if we want to separate out the fruits from this String i.e. get an array of fruits.

To do this we can use the split() method.

split()
In order to use split() we need to pass the character which needs to be used to perform the split.

let fruitArray = fruits.split(',');
fruitArray // ['Mango', 'Peach', 'Banana']
fruitArray[0] // Mango

To combine all the array elements back, so that we can get a String, we can use the join() method.

join()

fruitArray.join('-') // 'Mango-Peach-Banana'

Alternatively we can use the toString() method.

How to add and remove elements to or from an Array?

To add or remove an element at the end of the Array you can use push() and pop()

push()
push() lets us add an element to the end of the Array.

fruitArray.push('Orange')

pop()
pop() lets us remove an element from the end of the Array.

fruitArray.pop()

Similarly, to add or remove an element at the start of the Array you can use unshift() and shift()

Author: codesmartly

I am Enthusiastic about Learning new things and sharing my Knowledge. I like programming and have a pretty good background in Computer Science.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s