Skip to main content

Posts

Showing posts from March, 2020

How to check that an variable is an array in JavaScript ?

Check that a variable is an Array:- var data = [21,56,23,48,19], obj={}; Using a function: function isArray(x) {   return x.constructor.toString().indexOf("Array") > -1; } isArray(data);// true Using  a method of  ES 5: isArray() method of ES5  returns true if an variable is an array else false. var status= Array.isArray(data); console.log(status) //true var status= Array.isArray(obj); console.log(status) //false Using  a instanceof operator :  instanceof operator  returns true if an variable is created with a constructor else false. data instanceof Array; // return true obj instanceof Array; // return false

Methods which we can use with array in JavaScript.

Methods which we can use with an array in JavaScript:- Array : It is a collection of similar items in big brackets. Here Jobs is an array. It has different types of jobs name as string. var Jobs = ['Doctor', 'Engineer', 'Lawyer', 'Carpenter', 'Technician', 'Clerk', 'Manager','Electrician','CA','Labour']; includes() : This method checks in an array that a particular item it contains or not and if contain then return true else false. It is not supported by the Internet Explorer. var item = Jobs.includes('Postman'); console.log(item); //Output: false var item = Jobs.includes('CA'); console.log(item); //Output: true indexOf() : This method determine in an array that a particular item it contains or not and if contains then return it first index else -1. It is supported all browser. var item = Jobs.indexOf('Postman'); console.log(item); //Output: -1 var item = Jobs. indexOf (...

How get unique and sorted values from an array using JavaScript?

Get unique and sorted values from an array in JavaScript:- // Array need to make unique and sorted var Cities = ['Kolkata', 'Udaipur', 'Delhi', 'Mumbai', 'Chennai', 'Hyderabad', 'Bangalore','Chennai','Delhi','Mumbai']; Method 1: //an empty array declared let UniqueSortedCities = []; //loop use to iterate items of array Cities .forEach(function(c){     if(UniqueSortedCities.indexOf(c) == -1){ //using indexOf() method checking the values present in array        UniqueSortedCities.push(c);  // Using push() method we can add item/city in an array.     } }); //Using sort method we can sort an array. console.log(UniqueSortedCities.sort()); Output: ["Bangalore", "Chennai", "Delhi", "Hyderabad", "Kolkata", "Mumbai", "Udaipur"]; //unique and sorted array. Method 2: let UniqueSortedCities = []; Cities .forEach(function(c){ ...