Arrays

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type.

An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

arrays-index-system

Create Arrays in Nodejs

We can create the arrays in nodejs with following code. To create an empty array

 
var array = [];

To create an array with elements

 
var arr = [ 'cat', 'goat', 'bat' ];

Array functions

Index :

Access the array, we can access the nodejs array using index of the array, array index starts from 0. Index number is used along with [ ] operator.


var arr = [ 'cat', 'goat', 'bat' ];
console.log(arr[0]) // prints cat
console.log(arr[2]) // prints bat

Sometime you might need to print total array, in that case provide array without any index or fucntion to he console.log()


var arr = [ 'cat', 'dog', 'goat' ];
console.log(arr) // prints all elements

indexOf() :

indexOf method is used to return the first index of the element passed within the array or otherwise it will return -1 if the value is not found.


var arr = [ 'cat', 'dog', 'goat', 'mummy', 'goat' ];
console.log(arr) // prints 'cat', 'dog', 'goat', 'mummy', 'goat'
var position = arr.indexOf("avatar");
console.log(position)
//prints -1
console.log(arr.indexOf("goat"))
//prints 2

lastIndexOf() :

lastIndexOf method is used to return the last index of the element passed within the array or otherwise it will return -1 if the value is not found.


var arr = [ 'cat', 'dog', 'goat', 'cat'];
console.log(arr) // prints 'cat', 'dog', 'goat', 'cat'
var position = arr.lastIndexOf("avatar");
console.log(position)
//prints -1
console.log(arr.lastIndexOf("goat"))
//prints 3

push function :

push() function helps to cerate a object inside the array,


var arr = [ 'cat', 'dog', 'goat' ];
console.log(arr) // prints 'cat', 'dog', 'goat'
arr.push("human")
console.log(arr) // prints 'cat', 'dog', 'goat', 'human'

pop function :

pop() function removes the element from the end of the array. pop() does not accept any parameter


var arr = [ 'cat', 'dog', 'goat' ];
console.log(arr) // prints 'cat', 'dog', 'goat'
arr.pop()
console.log(arr) // prints 'cat', 'dog'

unshift function :

unshift() method in arrays is used insert an element in the beginning of the array


var arr = [ 'cat', 'dog', 'goat' ];
console.log(arr) // prints 'cat', 'dog', 'goat'
arr.unshift("pug")
console.log(arr) // prints 'pug', 'cat', 'dog', 'goat'

shift function :

shift() method is used to remove the element from the beginning of the array, shift() functions does not accept any parameter. pop remove the element from end of the array


var arr = [ 'cat', 'dog', 'goat' ];
console.log(arr) // prints 'cat', 'dog', 'goat'
arr.shift()
console.log(arr) // prints 'dog', 'goat'

splice() function in nodejs:

splice() function can be used in two ways i.e to either add the element into the array or remove the elements from the array.


array.splice(index, howMany, [element1][, ..., elementN]);


index − Index at which to start changing the array.

howMany − An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.

element1, ..., elementN − The elements to add to the array. If you don't specify any elements, splice simply removes the elements from the array.

If user provides index, howMany and values(elements) to the splice() function then splice() will insert the given details but if the we donot provide value then splice() function will remove element from the given index with howMany elements.


var arr = [ 1, 9, 3 ];
console.log(arr) // prints 1, 9, 3
// adds given elements from index 2
arr.splice(2,2,"abc", "bbc")
console.log(arr) // prints 1, 3, 'abc', 'bbc'
// remove 3 elements from given index
arr.splice(2,3)
console.log(arr) // prints 1, 3

sort() function in nodejs:

sort method is used to arrange the elements of array in ascending order


var arr = [ 1, 9, 3 ];
console.log(arr) // prints 1, 9, 3
arr.reverse()
console.log(arr) // prints 1, 3, 9

reverse() function in nodejs:

reverse() function is used to reverse the order of the array such that the first element becomes the last and the last element becomes the first.

reverse() function does not accept any parameter.

Sometimes you might need to sort the array in descending order but we do not have such functionality in nodejs.

In such kind of case, we can sort the array in ascending order then reverse it, so we will get descending order


var arr = [ 1, 9, 3 ];
console.log(arr) // prints 1, 9, 3
arr.reverse()
console.log(arr) // prints 3, 9, 1

concat()

concat method is used to join two arrays and returns a new array consisting the elements of both the arrays one after other.


arr = ['jack fruit','grape'];
arr2 = ['mango','kiwi','apple'];
console.log(arr);
console.log(arr2);
var new_arr = arr.concat(arr2);
console.log(new_arr);
//prints 'jack fruit','grape','mango','kiwi','apple'

join() :

join() method is used to join the array elements into a string and returns the string. The elements will be separated by a specific separator while joining the array elements, which will be passed while calling the method. The default separator is , (comma) .


var arr = [ 1, 9, 3 ];
console.log(arr) // prints 1, 9, 3
var combinedString = arr.reverse("=====")
console.log(combinedString) // prints 1=====9=====3

slice() function :

slice() function is used to extract a section of an array and returns a new array, it will not have any effect on Original array. Slice method take two arguments i.e start and end. If both elements are omitted then it will slice the whole array. Syntax is : slice(start,end)

start : it is an integer index which specifies from which index to start. The default value is index 0 . If we omit the start index like slice(,end) it will use the default value as start. We can also start from the end by using negative values . This is optional.

end : it is an integer value which specifies where to end (last index excluded). If we omit the end index like slice(start,) it will slice upto the last element. We can use negative values to select from the end. This is optional.

every() function :

every() function is used to check whether a condition in fulfilled by all the elements or not. every() function returns true if the condition is satisfied by all the elements of the array otherwise every method will return false .


arr = [1,3,7,11,13];
arr1 = [1,3,6,4,8];
function odd(value){
    if( (value % 2) == 1){
        return true;
    }else{
        return false;
    }
}

var out = arr.every(odd);
var out1 = arr1.every(odd);
console.log("Output of array 1 : " + out);
console.log("Output of array 2 :" + out1);

filter() function in nodejs :

filter() function is used to create a new array based on given condition, new array is filled with all the elements that passes a test condition usually passed as a function, from the current array.


arr = [1,3,7,11,13];
arr1 = [1,3,6,4,8];
function odd(value){
    if( (value % 2) == 1){
        return true;
    }else{
        return false;
    }
}

var out = arr.filter(odd);
var out1 = arr1.filter(odd);
console.log("Output of array 1 : " + out);
console.log("Output of array 2 :" + out1);

find() in nodejs :

find() function returns the first value in the array which passes a test provided as a function. If no element in the array matches the condition, it will return undefined


arr = [2,4,6,8,10];
arr1 = [2,3,4,7,8];
function odd(value){
    if( (value % 2) == 1){
        return true;
    }else{
        return false;
    }
}

var out = arr.find(odd);
var out1 = arr1.find(odd);
console.log("Output of array 1 : " + out);
console.log("Output of array 2 :" + out1);	

forEach() function :

The forEach() function works only on collections, and is used to loop through each keys in an array. Array is also one of the collection


var arr = ['karthiq', 'chercher tech', 'is','not','that much good website'];

arr.forEach(function(element) {
    console.log(element);
});	

// prints
karthiq
chercher tech
is
not
that much good website

reduce() function :

reduce() function is used to reduce the array to a single value, it method executes the provided function for each value of the array and stores the result in accumulator, it has no effect on array with no values.

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group