Arrays in JavaScript - It's properties and methods

Arrays in JavaScript - It's properties and methods

JavaScript Arrays

What is an Array?

Array is a collection of data seperated by "," inside the []- square brackets . The data can be of similar or different data types.

Note: If data is string then it must be written inside ' ' or " " followed by , (comma). if its boolean or number write them as it seperating with , (comma).

Syntax:

variable_declaration varaiable_name = [data1,data2,data3,.....];
(or)
variable_declaration varaiable_name = new Array(data1,data2,data3,.....);

Accessing Array Elements

Array elements can be accessed using index number. As usual the index will be starting from zero-index (0).

let arr=['welcome',2,'javascript',true] //'string',Number,'string',boolean
//          0      1       2        3
console.log(arr[2]); // array_name[index_No]
//output:javascript

We can iterate over arrays in general using for_loop, forEach_loop and for-of_loop Lets us now see more about Array properties and methods.

Array Properties

length

The length property sets or returns the number of elements in an array.

let arrayEx1=[1,2,3,4,5,6];
console.log(arrayEx1.length); //6

let arrayEx2=[1,2,3,4,5,6];
arrayEx2.length=3;
console.log(arrayEx2); // [ 1, 2, 3 ]

constructor

In JavaScript, the constructor property returns the constructor function for an object. For JavaScript arrays the constructor property returns function Array() { [native code] }

let arrayEx1=[1,2,3,4,5,6];
arrayEx1.constructor;
// ƒ Array() { [native code] }

prototype

The prototype constructor allows you to add new properties and methods to the Array() object.

// Making a prototype method for array Object which can be used later by any array instance object
Array.prototype.sumNum=function(){
    let sum=0;
    for(i=0;i<this.length;i++){
        sum+=this[i];
    }
    return sum;
}

let arrayEx1=[1,2,3,4,5,6];
arrayEx1.sumNum();
//output: 21

let arrayEx1=[1,2,3,'b',5,6];
arrayEx1.sumNum();
// '6b56'

Array Methods

push()

The push() method adds new items to the end of an array.

let colors=['blue','red','green'];
colors.push('white');
console.log(colors);
// ['blue', 'red', 'green', 'white']

pop()

The pop() method is used to remove the last element from an array.

let colors=['blue','red','green','white'];
colors.pop();
console.log(colors);
// ['blue', 'red', 'green']

shift()

The shift() method used to remove the first item of an array.

let colors=['blue','red','green','white'];
colors.shift();
console.log(colors);
// ['red', 'green', 'white']

unshift()

The unshift() method is used to add an item to the beginning of an array.

let colors=['blue','red','green','white'];
colors.unshift('black','yellow');
console.log(colors);
// ['black', 'yellow', 'blue', 'red', 'green', 'white']

slice()

The slice() method is used to create a copy of part of an array.it expects two arguments (start,end).it slices array from starting index mentioned as start argument until the end index (end index is not included).

let colors=['black','yellow','blue','red','green','white'];
let slicedArray=colors.slice(0,2);
console.log(slicedArray);
// ['black', 'yellow']

splice()

The splice() method adds/removes items to/from an array.

// To remove items from an array and return the new array Array.splice(start from index ,no.of values need to remove); //Array.splice(0,2)

//example:
let colors=['black','yellow','blue','red','green','white'];
colors.splice(0,2);
console.log(colors);
// ['blue', 'red', 'green', 'white']

// To add items to an array and return the new array Array.splice(start from index ,no.of values need to remove,items to be added); //Array.splice(0,0,"pink")

//example:
let colors=['black','yellow','blue','red','green','white'];
colors.splice(0,0,'pink');
console.log(colors);
// ['pink', 'black', 'yellow', 'blue', 'red', 'green', 'white']

concat()

The concat() method is used to join two or more arrays. This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.

let colors1=['blue','red','green','white'];
let colors2=['black','pink'];
let newColor=colors2.concat(colors1);
console.log('colors 1:',colors1);
console.log('colors 2:',colors2);
console.log('Concatenated colors:',newColor);
// colors 1:  ['blue', 'red', 'green', 'white']
// colors 2:  ['black', 'pink']
// Concatenated colors:  ['black', 'pink', 'blue', 'red', 'green', 'white']

entries()

The entries() method returns an Array Iterator object with key/value pairs.

let colors=['black','yellow','blue','red','green','white'];
let col=colors.entries();
console.log(typeof col)
for(let element of col){
    console.log(element);
}
// returns object containing array of key/value pair need to be iterated to access them.
// Array Iterator {} 
// [0, 'black']
// [1, 'yellow']
// [2, 'blue']
// [3, 'red']
// [4, 'green']
// [5, 'white']

every()

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

let ageList=[12,15,22,23,25,16,48];

function checkAdult(age){
    return age>=18;
}

ageList.every(checkAdult);
// false

fill()

The fill() method fills the specified elements in an array with a static value. You can specify the position of where to start(inclusive) and end(exclusive) the filling. If not specified, all elements will be filled.

let colors=['black','yellow','blue','red','green','white'];
// fill with "pink" from position 2 until position 4
console.log(colors.fill("pink",2,4));
// fill with "pink" from position 2 
console.log(colors.fill("pink",2));
// fill all items with "red" 
console.log(colors.fill("red"))
// ['black', 'yellow', 'pink', 'pink', 'green', 'white']
// ['black', 'yellow', 'pink', 'pink', 'pink', 'pink']
// ['red', 'red', 'red', 'red', 'red', 'red']

filter()

The filter() method is used to check which are the items in an array is passing certain condition will be returned as output array which can be stored in another variable for later use.

let ageList=[18,15,22,23,25,16,48];

function checkAdult(age){
    return age>=18;
}

ageList.filter(checkAdult);
// [18, 22, 23, 25, 48]

find

The find() method returns the first item which is passing certain condition in an array.

let ageList=[15,22,18,23,25,16,48];

function checkAdult(age){
    return age>=18;
}

ageList.find(checkAdult);
// 22

findIndex()

The findIndex() method returns the index of the first element in an array that pass a test or condition.

let ageList=[15,22,18,23,25,16,48];

function checkAdult(age){
    return age>=18;
}

ageList.findIndex(checkAdult);
// 1

indexOf()

The indexOf() method searches the array for the specified item, and returns its position.

let colors=['black','yellow','blue','red','green','white'];
let color=colors.indexOf("red");
console.log(color);
// 3

latIndexOf()

The lastIndexOf() method searches the array for the specified item, and returns its last position.

let colors=['black','yellow','red','blue','red','green','white'];
let color=colors.lastIndexOf("red");
console.log(color);
// 4

forEach()

The forEach() method executes a provided function once for each array element.

let colors=['black','yellow','red','blue','red','green','white'];
colors.forEach(function(data){
    console.log(data.toUpperCase());
})
// BLACK
// YELLOW
// RED
// BLUE
// RED
// GREEN
// WHITE

includes()

The includes() method determines whether an array contains a specified element.

// includes(searchElement)
let colors=['black','yellow','red','blue','red','green','white'];
console.log(colors.includes("red"));
// true
// includes(searchElement, fromIndex) 
let colors=['black','yellow','red','blue','red','green','white'];
console.log(colors.includes("red",3));
// true

let colors=['black','yellow','red','blue','red','green','white'];
console.log(colors.includes("red",5));
// false

isArray()

The isArray() method determines whether an object is an array.This method returns true if the object is an array, and false if not.

let colors=['black','yellow','red','blue','red','green','white'];
let result=Array.isArray(colors)
console.log(result);
// true

join()

The join method is used to convert the elements of an array into a string. This method returns the array as a string.

let colors=['black','yellow','red','blue','red','green','white'];
//array.join(connector by which each element to be joined)
let result=colors.join(" and ");
console.log(result);
// black and yellow and red and blue and red and green and white

map()

The map() method creates a new array with the results of calling a function for every array element.

let num=[1,2,3,4,5,6];
let res=num.map(Math.sqrt);
console.log(res);
// [1, 1.4142135623730951, 1.7320508075688772, 2, 2.23606797749979, 2.449489742783178]

reverse()

The reverse() method reverses the order of the elements in an array.

let num=[1,2,3,4,5,6];
let res=num.reverse();
console.log(res);
// [6, 5, 4, 3, 2, 1]

sort()

The sort() method is used to sort elements in ascending order first numbers sorted and then alpha characters are sorted. In descending order its vice versa alpha first and numbers second. we can sort in descending order by : first sort using sort() method followed by reverse() method

// default sort
let num=[1,2,3,4,5,'a',6];
let res=num.sort();
console.log(res);
// [1, 2, 3, 4, 5, 6, 'a']

//sort desc
let num=[1,2,3,4,5,'a',6];
let res=num.sort().reverse();
console.log(res);
// ['a', 6, 5, 4, 3, 2, 1]

reduce()

The reduce() method walks through the array element-by-element, at each step adding the current array value to the result from the previous step.

let num=[1,2,3,4,5,6];
// reduce((previousValue, currentValue)=>{},initialValue)
//previousValue-->arr[0] by default if initial value is not mentioned.
let res=num.reduce((previousValue, currentValue)=>previousValue+currentValue,0);
console.log(res);
// 21

reduceRight()

The reduceRight() method executes a provided function for each value of the array (from right-to-left) .we can understand them by example.

// example of subtracting elements using reduce (which iterates through left-to-right)
let num=[1,2,3,4,5,6];
// reduce((previousValue, currentValue)=>{},initialValue)
//previousValue-->arr[0] by default if initial value is not mentioned.
let res=num.reduce((previousValue, currentValue)=>previousValue-currentValue);
console.log(res);
// -19

// example of subtracting elements using reduceRight (which iterates through right-to-left)
let num=[1,2,3,4,5,6];
// reduce((previousValue, currentValue)=>{},initialValue)
//previousValue-->arr[0] by default if initial value is not mentioned.
let res=num.reduceRight((previousValue, currentValue)=>previousValue-currentValue);
console.log(res);
// -9

some()

The some() method checks if any one of the elements in an array pass a test . It executes the function once for each element present in the array

// any one item passing the criteria will return TRUE.
let ageList=[15,22,18,23,25,16,48];

function checkAdult(age){
    return age>=18;
}

ageList.some(checkAdult);
// true

toString()

The toString() method returns a string with all the array values, separated by commas.

let colors=['black','yellow','red','blue','red','green','white'];
let result=colors.toString();
console.log(result);
// black,yellow,red,blue,red,green,white

valueOf()

The valueOf() method simply returns the values of an array.

let colors=['black','yellow','red','blue','red','green','white'];
let result=colors.valueOf();
console.log(result);
// ['black', 'yellow', 'red', 'blue', 'red', 'green', 'white']

These are the few useful Array properties and methods. Hope this article will be useful.

THANK YOU! Happy Coding 😊