JavaScript: Array
Kiran Raj R
Posted on April 21, 2021
An array is an ordered collection of elements of same or different data types. The length or the data type of the array is not fixed in JavaScript. Array use integer values as index, starting from zero. Accessing an array element is done using bracket notation
Creating an Array
We can create an array using array literal syntax or using the new operator.
1.Using an array literal syntax
// Empty array
let arr = [];
// Array of numbers
const arrNums = [1,2,3,4];
// Array of characters
const arrAlpha = ['a', 'b', 'c', 'd'];
// Array of functions
const arrFun = [function print1 () {console.log(1)},
function print2 () {console.log(2)}, ];
//Multidimensional Array
let mArray = [['a', 'apple'], ['b', 'ball'], ['c', 'cat']];
2.Using the new keyword
const emptyArr = new Array();
const arrString = new Array("the", "an", "a", "am");
const arrMixed = new Array("hello", 123, true, false);
let emptyArrLen = new Array(10);
console.log(emptyArrLen.length); // 10
Accessing an array
Array elements are accessed using index in bracket notation. Array index starts at zero.
const arrNums = [1,2,3,4];
const arrAlpha = ['a', 'b', 'c', 'd'];
console.log(arrAlpha[0]); // a
console.log(arrNums[3]); // 4
Add an element to an array
You can add element to array using array literal syntax. Specify the index of the array where you want to add the element just assign the value to it. If the index already contain an value/element where you want to add the value/element, it will be replaced with the new value/element. If there are any unassigned indexes before the specified index it will be set to undefined.
const arrAlpha = ['a', 'b', 'c', 'd'];
arrAlpha[4] = "added";
console.log(arrAlpha); // ["a", "b", "c", "d", "added"]
arrAlpha[6] = "six";
console.log(arrAlpha);
// ["a", "b", "c", "d", "changed", undefined, "six"]
console.log(arrAlpha[5]) // undefined
Changing an array element
Access the array element you want to change, assign new value to that index.
arrAlpha = ["a", "b", "c", "d", "added"]
arrAlpha[4] = "changed";
console.log(arrAlpha); // ["a", "b", "c", "d", "changed"]
Array Length
Array length can be found by arrayName.length
property.
const arrNums = [1,2,3,4,5];
const arrString = new Array("the", "an", "a", "am");
console.log(arrNums.length); // 5
console.log(arrString.length); // 4
There is a problem with length
, it is not returning the actual number of elements, it is returning one more than the last index value of the array. Check the code below.
let arrLen = [1,2,3,4,5];
arrLen[100] = 100;
console.log(arrLen.length); // 101
// 101 elements in arrLen ??
// Number of elements in the array that are not undefined
function arrLength(arr){
let count = 0;
arr.forEach(element =>{
if (element != undefined){
count++;
}
});
return count;
}
// Actual number of elements
let count = arrLength(arrLen);
console.log(count); // 6
We can set the array length, even if the current length is more than the value we set, any element after the index will be set to undefined.
let arrLen = [1,2,3,4,5];
arrNums.length = 3;
console.log(arrNums); // [1, 2, 3]
console.log(arrNums[3]); // undefined
Adding elements to array
We saw that we can add elements to array using array literal method.
const arrAlpha = ['a','b','c','d'];
arrAlpha[4] = "added";
console.log(arrAlpha); // ["a", "b", "c", "d", "added"]
Apart from that, there are build in methods to add elements to an array,
- push method
- unshift method
1.Push()
push
method help to add element at the back(top) of an array.
arrNums = [1,2,3,4,5];
arrAlpha = ['a','b','c','d'];
arrNums.push(6);
console.log(arrNums); // [1, 2, 3, 4, 5, 6]
arrAlpha.push('z');
console.log(arrAlpha); // ["a", "b", "c", "d", "z"]
2.Unshift()
unshift
method add element to the front of the array.
arrNums = [1, 2, 3, 4, 5];
arrAlpha = ['a', 'b', 'c', 'd'];
arrNums.unshift(0);
console.log(arrNums); // [0, 1, 2, 3, 4, 5]
arrAlpha.unshift('aa');
console.log(arrAlpha); // ["aa", "a", "b", "c", "d"]
Remove elements from array
There are built in methods to remove elements from an array
- pop()
- shift()
1.Pop ()
pop()
method removes the last element from the array. The pop method return the removed element.
arrNums = [1, 2, 3, 4, 5];
arrAlpha = ['a', 'b', 'c', 'd'];
let pop1 = arrNums.pop(); // 5
console.log(arrNums); // [1, 2, 3, 4]
console.log(pop1);
let pop2 = arrAlpha.pop();
console.log(pop2); // d
console.log(arrAlpha); // ["a", "b", "c"]
2.Shift()
shift
method removes the first element of an array. shift
method returns the removed element.
arrNums = [1, 2, 3, 4, 5];
arrAlpha = ['a', 'b', 'c', 'd'];
let shift1 = arrNums.shift();
console.log(shift1); //1
console.log(arrNums); // [2, 3, 4, 5]
let shift2 = arrAlpha.shift();
console.log(shift2); // a
console.log(arrAlpha); // ["b", "c", "d"]
To loop through the array elements you can use for
loop or for...of
loop
arrNums = [1, 2, 3, 4, 5];
for( i=0; i<arrNums.length; i++){
console.log(arrNums[i]) // 1 2 3 4 5
}
for(elem of arrNums){
console.log(elem); // 1 2 3 4 5
}
Array Methods
1.Reverse Method
Reverse method reverse the current order of the array, the change is made on the original array not on a copy. The method do not take any arguments, the reversed array is returned by the method.
//syntax
arr.reverse();
let arr1 = [5,4,7,3,9];
let arr1Rev = arr1.reverse();
console.log(arr1Rev); //[9, 3, 7, 4, 5]
2.Sort Method
Sort method sort the array elements in a specific ascending or descending order. The sorting is done on the original array, not on a copy, the return value of the method is the sorted array. It takes an optional parameter, comparisonFunction
, the function is used to sort the elements of the array. By default the sort function converts the array elements which are not undefined into strings, then they are compared with UTF-16 code point value, (if the comparisonFunction is not passed). If no parameter is provided then the elements are arranged in ascending order of the UTF-16 code point value. Undefined elements are placed last in the array.
//syntax
arr.sort();
let numArr = [11,22,13,67,51,33, 12];
let sortNumArr = numArr.sort();
console.log(sortNumArr); //[11, 12, 13, 22, 33, 51, 67]
Let's look at another example
let numArrBogus = [22, 56, 34, 1000, 200, 300, 10 ,23,1];
let bogusArr = numArrBogus.sort();
console.log(bogusArr); // [1, 10, 1000, 200, 22, 23, 300, 34, 56]
In the above code you can see that 1000 is place before 22, 23; 200 is placed before 22. What is happening here?? As I told you earlier the JavaScript engine converts the elements into strings, string "1000" has a UTF-16 code point value less than that of string "22".
Lets pass an comparison function to sort
let namesArr = ["kiran", "manu", "vishnu", "adithyan"];
function sortLength(a,b){
a = a.length;
b = b.length;
return a - b
}
let sortedArr = namesArr.sort(sortLength);
console.log(sortedArr)
//["manu", "kiran", "vishnu", "adithyan"]
function sortVal(a,b){
a = parseInt(a)
b = parseInt(b)
return a - b
}
let sortedBogus = numArrBogus.sort(sortVal);
console.log(sortedBogus)
//[1, 10, 22, 23, 34, 56, 200, 300, 1000]
When function is passed as parameter(comparisonFunction
), it is not called to evaluate the undefined elements, undefined elements are placed at the end of the array. The remaining elements are sorted based on the return value of the compareFunction. The sort method pass two values at a time to the comparisonFunction
to compare, the function must return a number, which is used to sort the array. There are three possibilities for the return value of the comparisonFunction
.
Returned value < 0, value1 is placed before value2.
Returned value > 0, value2 is placed before value1.
Returned value == 0, value1 and value2 will not change their positions.
3.Concat Method
Concat method takes multiple array and/or values as parameters and create a new array by merging the elements of all the arrays and values together. Elements added in the order in which they are provided to the concat method.
//Syntax
arr.concat(arr1, arr2.....arrN);
// Concat Method
let arr1 = [1,2,3,4,5];
let arr2 = [10, 12, 14];
let arr3 = [100, 101];
let arr4 = arr1.concat(arr2, arr3, 200, 300);
console.log(arr4);
//[1, 2, 3, 4, 5, 10, 12, 14, 100, 101, 200, 300]
let arrnest = [[1,2,3],5,7,6];
let mergArr = arrnest.concat([10,100,12], 100, 120);
console.log(mergArr); //[[1,2,3]], 5, 7, 6, 10, 100, 12, 100, 120]
Let's look at one more example
let arr10 = [1, 2, 3,[100, 200]];
let arr11 = [5,10,15];
let arr12 = [100, 110, 120];
let newArr = arr10.concat(arr11, arr12);
console.log(newArr);
//[1, 2, 3, [100, 200], 5, 10, 15, 100, 110, 120]
arr10.push(111);
console.log(newArr);
// [1, 2, 3, [100, 200], 5, 10, 15, 100, 110, 120]
arr11.push(1111);
console.log(newArr);
// [1, 2, 3, [100, 200], 5, 10, 15, 100, 110, 120]
// no change in newArr after the push operations on arr10 or arr11
arr10[3].push(300);
console.log(newArr);
// [1, 2, 3, [100, 200, 300], 5, 10, 15, 100, 110, 120]
// newArr get updated, nested elements are passed as references.
From the above example we can understand that nested arrays' are copied by references, so any change in nested array will be updated to the result array.
4.IndexOf()
We use indexOf method to search for an element in the array, indexOf method returns the index of the element's first occurrence. It takes two arguments, the element to search for and an optional index position, from where the search must start, ignoring elements before it. If the second parameter is not provided the search starts from index 0. The method return the first occurrence of the element, elements after it is ignored. -1 is returned if the element is not found in the array.
Let's look at an example
let arr1 = [1,2,3,4,5,6,7,8,9,0];
let result1 = arr1.indexOf(5);
console.log(result1); // 4
let arr2 = ['a', 'aa', 'aaa', 'aa', 'a', 'bb', 'c'];
let result2 = arr2.indexOf('aa');
console.log(result2); // 1
let result3 = arr2.indexOf('aa', 2);
console.log(result3); // 3
let result4 = arr2.indexOf('z');
console.log(result4) //-1
// Function to find all the occurance
function findAll(arr, elem){
let indexarr= [];
for (i=0; i<arr.length; i++) {
if (arr[i] === elem){
indexarr.push(i)
}
}
return indexarr;
}
console.log(findAll(arr2, 'a')); [0, 4]
There is something to note, if you provide position index greater than the length of the array, -1 is returned without any search.
5.lastIndexOf()
LastIndexOf method returns the index of "last" occurrence of an element we passed to the method to search. The search starts from the back and ends at index zero. It takes two arguments, the element to search for and an optional index position, from where the search must start, backwards. If the second parameter is not provided the search starts from the last element(array.length - 1
). -1 is returned if the element is not found.
// lastIndexOf
let arr20 = [1,2,3,4,5,6,7,8,9,0];
let result10 = arr20.lastIndexOf(5);
console.log(result10); // 4
let arr21 = ['a', 'aa', 'aaa', 'aa', 'a', 'bb', 'c'];
let result20 = arr21.lastIndexOf('aa'); // 3
console.log(result20);
let result30 = arr21.lastIndexOf('a'); // 4
console.log(result30);
6.Includes Method
Includes method checks whether a given element is in the array or not, if found it will return true, else false. It takes two parameter, the value to search and an optional parameter, which specify from which index the search begins, by default the value is zero.
// syntax
arr.includes(val, index)
let array1 = [10,20,30,15,25];
console.log(array1.includes(30)); // true
console.log(array1.includes(300)); // false
7.Array splice()
The splice method can modify an array by inserting new element, deleting the existing element or by replacing the elements with new elements. Splice method returns the removed elements as an array.
//syntax
arr.splice(start, deleteCount, elem1, ..., elemN])
// start specifies the start position for the splice operation.
// deleteCount specifies the number of elements to delete.
// elem1....elemN indicates the elements to be inserted.
Lets look at an example
let arr1 = [1,2,3,4,5,10,20];
let r1 = arr1.splice(3);
console.log(r1); // [4, 5, 10, 20]
console.log(arr1); // [1, 2, 3]
let arr2 = [1,2,3,4,5,10,20,100,200];
let r2 = arr2.splice(0,3);
console.log(r2); // [1, 2, 3]
console.log(arr2); // [4, 5, 10, 20, 100, 200]
let arr3 = [11,33,43,100,98,10,20,55];
let r3 = arr3.splice(3);
console.log(r3); // [100, 98, 10, 20, 55]
console.log(arr3); // [11, 33, 43]
From the above code we can see that the splice with only the start
will remove all the elements including the element at the start
index, if we specify the start
and deleteCount
, deleteCount
elements from the start
position(including the start
index) are removed.
We can insert element using splice method, just keep the deletecount
to zero, specify the start
(index where you want to insert the elements) and elements that need to be inserted (elem1....elemN
).
// insertion
let arr4 = [];
//insert element at index 0
arr4.splice(0,0,1,2,3,4);
// first zero is start, second zero deleteCount
// remaining are elements to be added to the array
console.log(arr4); // [1, 2, 3, 4]
// insert element at index 4
arr4.splice(4,0,14,24,34,44);
console.log(arr4); // [1, 2, 3, 4, 14, 24, 34, 44]
arr4.splice(10,0,50,51,52,53);
console.log(arr4); //[1, 2, 3, 4, 14, 24, 34, 44, 50, 51, 52, 53]
// we try to insert element at index 10, as the length of the
// array is 8, so the elements are added at the end of the array
// insert element at index 0
arr4.splice(0,0,100,200);
console.log(arr4);
//[100, 200, 1, 2, 3, 4, 14, 24, 34, 44, 50, 51, 52, 53]
We can use splice to replace elements, let's look at an example
// replace elements
let myArr = [1,2,3,4,5];
let res1 = myArr.splice(3,2,40,50);
console.log(myArr); //[1, 2, 3, 40, 50]
console.log(res1); //[4,5]
8.Array slice()
Slice method returns a new array which is a shallow copy of the array on which the method is invoked. Slice method take two parameters, start
and end
, both are optional, start
has a default value of 0. The returned array contains elements from start
index to end
index(end is excluded). If no parameter is passed the array will be repeated without any change. If only start
index is specified all elements from the start
index to the last index of the array is returned.
let newArr = [1,2,3,4,5];
let subArr = newArr.slice(2);
console.log(subArr); // [3, 4, 5]
console.log(newArr); // [1, 2, 3, 4, 5]
let subArr1 = newArr.slice();
console.log(subArr1); // [1, 2, 3, 4, 5]
// slice all elements
let subArr2 = newArr.slice(0);
console.log(subArr2); // [1, 2, 3, 4, 5]
// slice elements from index 0 to array end
let subArr3 = newArr.slice(1,3);
console.log(subArr3); // [2, 3]
// slice elements from index 1 to index 2
let subArr4 = newArr.slice(1,-1);
console.log(subArr4); // [2, 3, 4]
// slice elements from index 1 to index length-2
9.Join method
join() method returns a new string by concatenating all of the elements of the array separated by a user specified string or by the default string(comma). The method takes only one parameter, it is optional, a string that will be used to separate array elements. Undefined, null and empty arrays are converted into empty string. All the modification are done on the copy of the array not on the original array. Single element arrays are returned without using the separator.
let myName = ["k", "i", "r", "a", "n"];
let name = myName.join("");
console.log(name); // kiran
let nameColon = myName.join(":");
console.log(nameColon); // k:i:r:a:n
let name1 = myName.join();
console.log(name1); // k,i,r,a,n
Posted on April 21, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.