In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. Unlike most languages where array is a reference to the multiple variable, in JavaScript array is a single variable that stores multiple elements.
In this article, we will discuss 3 Array Methods JavaScript for Developers:
join()
split()
sort()
Why should every JavaScript developer know these methods? Arrays are important elements you’ll need in your code. These methods can help make your code more elegant and presentable.
You can make your project run without these methods, but for that, you will have to write unnecessary lines of code, of which there was no use in the first place.
So, let’s get started. We will first see some basic methods like join()
and split()
, and then we will move to sort()
.
Think of a scenario where users input some values in an array and later want to see it as a message (string).
This is where the join()
method comes in; it converts elements of an array into a string.
toString()
is also used to convert a string into an array, but with join()
, we can use a separator argument, so it’s better practice to use join()
.
The syntax is very simple. You just use:
array.join(separator)
Here, the separator is optional for the argument you pass, to define how you want the elements in the array to separate. It can be a space, a dot, a comma, a word, etc.
If no argument is passed, its elements are separated by a comma.
Let’s see it in action.
const array1=[1,2,3,'My','Name','is','Ney']
const string1=array1.join()
const string2=array1.join('')
const string3=array1.join(',')
const string4=array1.join('and')
const string5=array1.join('-')
const string6=array1.join('=')
const string7=array1.join(':')
const string8=array1.join(' ')
console.log(array1)
// [ 1, 2, 3, 'My', 'Name', 'is', 'Ney' ]
console.log(string1)
// 1,2,3,My,Name,is,Ney
console.log(string2)
//123MyNameisNey
console.log(string3)
// 1,2,3,My,Name,is,Ney
console.log(string4)
// 1and2and3andMyandNameandisandNey
console.log(string5)
// 1-2-3-My-Name-is-Ney
console.log(string6)
// 1=2=3=My=Name=is=Ney
console.log(string7)
// 1:2:3:My:Name:is:Ney
console.log(string8)
// 1 2 3 My Name is Ney
I want to point out an important aspect of string8
and string2
.
In string2
, there’s nothing between the quotation marks while there is a single space between them in string8
.
You can put any amount of space between them, and the result will change accordingly.
So, we have seen that we can convert elements in an array to a string.
What about converting a string into elements of an array? That’s what the split()
method does.
split()
can come in handy in situations where you have to take an input message and see if it contains a specific word or not. You can easily do so by converting the message to an array and using the includes()
method. We’ll talk about that soon.
Thesplit()
method is used to split a string into an array of substrings and returns the new array.
You can perform many other functions once the string is converted into an array. Technically, split()
is a string method, but I will discuss it here.
First, let us look at its syntax:
string.split(separator, limit)
Let’s see some examples.
const string1 = `1,2,3,My,Name,is,Ney`
const array1 = string1.split(',')
const arrayWithLimit = string1.split(',', 4)
const arrayWithoutSeperator = string1.split()
console.log(array1, arrayWithLimit, arrayWithoutSeperator)
//[ '1', '2', '3', 'My', 'Name', 'is', 'Ney' ] [ '1', '2', '3', 'My' ] [ '1,2,3,My,Name,is,Ney' ]
const string2 = `123MyNameisNey`
const array2 = string2.split('')
console.log(array2)
//[ '1', ',', '2', ',', '3', ',', 'M', 'y', ',', 'N', 'a', 'm', 'e', ',', 'i', 's', ',', 'N', 'e', 'y' ]
const string3 = `1,2,3,My,Name,is,Ney`
const array3 = string3.split(',')
console.log(array3) //[ '1', '2', '3', 'My', 'Name', 'is', 'Ney' ]
const string4 = `1and2and3andMyandNameandisandNey`
const array4 = string4.split('and')
console.log(array4) //[ '1', '2', '3', 'My', 'Name', 'is', 'Ney' ]
const string5 = `1-2-3-My-Name-is-Ney`
const array5 = string5.split('-')
console.log(array5) //[ '1', '2', '3', 'My', 'Name', 'is', 'Ney' ]
const string6 = `1=2=3=My=Name=is=Ney`
const array6 = string6.split('=')
console.log(array6) //[ '1', '2', '3', 'My', 'Name', 'is', 'Ney' ]
const string7 = `1:2:3:My:Name:is:Ney`
const array7 = string7.split(':')
console.log(array7) //[ '1', '2', '3', 'My', 'Name', 'is', 'Ney' ]
const string8 = `1 2 3 My Name is Ney`
const array8 = string8.split(' ')
console.log(array8) //[ '1', '2', '3', 'My', 'Name', 'is', 'Ney' ]
Now, let’s look at the above example one-by-one.
array1
, string1
: Split into an array wherever there was a comma.arrayWithLimit
: I have specified a limit, so the resulting array has only four starting elements, which was the limit.arrayWithoutSeperator
: I’ve already discussed that, if no separator is given, the whole string converts into a single element of the array.array2
: Because the quotation in the argument was empty, split()
separated each character, including white spaces, commas, and any other character if there was any.array4
: You will see all the “and” was missing from the string and the string that was left out became a single element of the array. If there was even a single alphabet in the argument, the result would be elements with a string missing the specified element. Try it out yourself. So, be careful when using words or strings as a separator.join()
did with respective characters.You could now practice creating a function with join()
, split()
, and reverse()
to check if the user input string is a palindrome.
If you aren’t familiar with the reverse()
method, it just reverses the elements of an array.
Here is an example:
const num = [1,2,3,4,5,6]
const reverseNum = num.reverse()
console.log(reverseNum) //[ 6, 5, 4, 3, 2, 1 ]
Try the practice problem and share the GitHub repository to your code in the comments.
As the name suggests, the sort()
method sorts the elements of an array.
By default, the sort()
function sorts values as strings.
let greekLetter = ['beta','alpha','delta','gamma'];
console.log(greekLetter.sort()) // [ 'alpha', 'beta', 'delta', 'gamma' ]
Now, a problem arises when you sort numbers.
Because, if I were to sort numbers, let’s say 100 and 25, 100 will come before 25, as 1 of 100 comes before 2 of 25.
let num1 = [25, 100, 23]
console.log(num1.sort()) //[ 100, 23, 25 ]
let num2 = ['25', '100', '23']
console.log(num2.sort()) //[ '100', '23', '25' ]
It can be fixed using a compare function, where a function is passed to syntax:function(a, b){return a — b}
let num = [25, 100, 23]
console.log(num.sort((a, b) => {
return a - b
}))
//[ 23, 25, 100 ]
(I have used an arrow function instead of traditional function declarations as given in the syntax above.)
Let’s understand this compare function. It should return a negative, zero, or positive value, depending on the arguments — whether a
is larger or b
.
When the sort()
function compares two values, it sends the values to the compare function and sorts the values according to the returned (negative, zero, positive) value.
a
is sorted before b
.b
is sorted before a
.0
, no changes are made to the sorted order of the two values.sort()
method calls the compare function (25, 100).This brings us to the end of this discussion.
We have successfully covered join()
, split()
, and sort()
.
In my next post, I will discuss the map()
and filter()
functions and why they are important to a programmer.
Thanks for reading!
#js #javascript