Guide to arrays in javascript
1. What is an array?
An array is an object where you store information in a list-like order. You can store information in an array without creating multiple variables.
1.1. Creating an array
Arrays can be created as
var arr1 = [];
var arr2 = new Array();
var arr1 = []
creates an array using an array literal and var arr2 = new Array()
creates an array using a constructor.
1.2. Initializing an array with values
You can add values to the array while initializing as shown below
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var fruits = new Array("mango","apple","banana");
Note: When adding integers using a constructor make sure to pass more than one value. Otherwise, it will think that you want to set the length of the array. If you want to add only one integer then use the array literal instead.
2. Converting an array to a string
You can convert all the elements to a single string using toString()
var numbers= [1, 2, 3, 4, 5, 5, 6, 7, 8, 9];
console.log(numbers.toString());
Output: 1,2,3,4,5,5,6,7,8,9
You can also use join()
. This will join all the elements together in a single string.
var numbers= [1, 2, 3, 4, 5, 5, 6, 7, 8, 9];
console.log(numbers.join());
Output: 1,2,3,4,5,5,6,7,8,9
Note: join() also takes a parameter which it will put in between two elements before joining them together.
For example:
var numbers= [1, 2, 3, 4, 5, 5, 6, 7, 8, 9];
console.log(numbers.join("-"));
Output: 1-2-3-4-5-5-6-7-8-9
3. Adding elements at the end of an array
To add an element at the end just use push()
var numbers= [1, 2, 3, 4, 5, 5, 6];
numbers.push(7);
numbers.push(8);
console.log(numbers);
Output: [ 1, 2, 3, 4, 5, 5, 6, 7, 8 ]
4. Appending an array to the end of another array
To append an array at the end of another array use the method concat()
var arr1 = ['Monday','Tuesday','Wednesday'];
var arr2 = ['Thursday','Friday','Saturday'];
var days = arr1.concat(arr2);
console.log(days);
Output: [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]
5. Reversing the order of elements of an array
reverse()
method is used to reverse the order of elements of an array.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
numbers.reverse();
console.log(numbers);
Output: [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
6. Getting the index number of an element in the array
To get the index number of an element we can use indexOf()
var days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
console.log(days.indexOf("Friday"));
Output: 4
7. Conclusion
In this article, we saw some useful built in methods that javascript provides us to work with arrays.