Found 6710 Articles for Javascript

Stop making form to reload a page in JavaScript

AmitDiwan
Updated on 18-Aug-2020 07:08:16

8K+ Views

Let’s say what we need to achieve is when the user submits this HTML form, we handle the submit event on client side and prevent the browser to reload as soon as the form is submittedHTML form Now, the easiest and the most reliable way of doing so is by tweaking our ValidateEmail() function to include the following line right at the top of its definition −function ValidateEmail(event, inputText){    event.preventDefault();    //remaining function logic goes here }What preventDefault() does is that it tells the browser to prevent its default behaviour and let us handle the form submitting ... Read More

Convert object of objects to array in JavaScript

AmitDiwan
Updated on 18-Aug-2020 07:06:34

3K+ Views

Let’s say we have the following object of objects that contains rating of some Indian players, we need to convert this into an array of objects with each object having two properties namely name and rating where name holds the player name and rating holds the rating object −Following is our sample object −const playerRating = {    'V Kohli':{       batting: 99,       fielding: 99    },    'R Sharma':{       batting: 98,       fielding: 95    },    'S Dhawan':{       batting: 92,       fielding: 90 ... Read More

How to import local json file data to my JavaScript variable?

AmitDiwan
Updated on 12-Sep-2023 00:57:00

34K+ Views

We have an employee.json file in a directory, within the same directory we have a js file, in which we want to import the content of the json file.The content of employees.json −employees.json"Employees" : [    {       "userId":"ravjy", "jobTitleName":"Developer", "firstName":"Ran", "lastName":"Vijay",       "preferredFullName":"Ran Vijay", "employeeCode":"H9", "region":"DL", "phoneNumber":"34567689",       "emailAddress":"ranvijay.k.ran@gmail.com"    },    {       "userId":"mrvjy", "jobTitleName":"Developer", "firstName":"Murli", "lastName":"Vijay",       "preferredFullName":"Murli Vijay", "employeeCode":"A2", "region":"MU",       "phoneNumber":"6543565", "emailAddress":"murli@vijay.com"       }    ] }We can use any of the two ways to access the json file −Using require ... Read More

Is there any way I can call the validate() function outside the initValidation() function in JavaScript?

AmitDiwan
Updated on 18-Aug-2020 07:02:11

177 Views

We wish to call the function validate() outside of initValidation(), without necessarily having to call initValidation()Following is our problem code −function initValidation(){    // irrelevant code here    function validate(_block){       // code here    } }In JavaScript, as we know that functions are nothing but objects, so to achieve this we can tweak our code like this −function initValidation(){    // irrelevant code here    function validate(_block){       // code here       console.log(_block);    }    this.validate = validate; }What this tweak does is that it makes our parent function to represent a ... Read More

Sorting by 'next' and 'previous' properties (JS comparator function)

AmitDiwan
Updated on 18-Aug-2020 07:00:57

356 Views

Here is our sample array of object, consider each object as representing some page of a multipage website, each object have a next property (unless it represents the last page) that points to some id of another object and a previous property (unless it represents the first page) that points to some id of its previous object.These objects are all positioned randomly right now, our job is to sort them to their correct position −let arr = [    { id: "1325asdfasdasd", next: "5345341fgdfgdd", previous:"545234123fsdfd" },    { id: "das987as9dya8s", next: "3j12k3b1231jkj" },    { id: "89ad8sasds9d8s", previous: "1j3b12k3jbasdd" }, ... Read More

Sorting arrays by two criteria in JavaScript

AmitDiwan
Updated on 18-Aug-2020 06:58:19

3K+ Views

Let the following be the array to be sorted by date and isImportant. All the objects with isImportant property true rank higher than any any of the object with isImportant false and both the groups sorted according to the date property.Following is our array −const array = [{    id: 545,    date: 591020824000,    isImportant: false, }, {    id: 322,    date: 591080224000,    isImportant: false, }, {    id: 543,    bdate: 591080424000,    isImportant: true, }, {    id: 423,    date: 591080225525,    isImportant: false, }, {    id: 135,    date: 591020225525,    isImportant: ... Read More

How do I search through an array using a string, which is split into an array with JavaScript?

AmitDiwan
Updated on 18-Aug-2020 06:56:19

226 Views

We are given an array of strings and another string for which we are required to search in the array. We can filter the array checking whether it contains all the characters that user provided through the input.The code for doing the same would be −ExampleSolution 1const deliveries = ["14/02/2020, 11:47, G12, Kalkaji", "13/02/2020, 11:48, A59, Amar Colony"]; const input = "g12, kal"; const pn = input.split(" "); const requiredDeliveries = deliveries.filter(delivery => pn.every(p => delivery.toLowerCase() .includes(p.toLowerCase()))); console.log(requiredDeliveries);OutputThe output in console −["14/02/2020, 11:47, G12, Kalkaji"]In another and a bit better approach we can remove the step of splitting the input ... Read More

Is it possible to have JavaScript split() start at index 1?

AmitDiwan
Updated on 18-Aug-2020 06:55:16

355 Views

As of the official String.prototype.split() method there exist no way to start splitting a string from index 1 or for general from any index n, but with a little tweak in the way we use split(), we can achieve this functionality.We followed the following approach −We will create two arrays −One that is splitted from 0 to end --- ACTUALSecond that is splitted from 0 TO STARTPOSITION --- LEFTOVERNow, we iterate over each element of leftover and splice it from the actual array. Thus, the actual array hypothetically gets splitted from STARTINDEX to END.Exampleconst string = 'The quick brown fox ... Read More

Flat a JavaScript array of objects into an object

AmitDiwan
Updated on 18-Aug-2020 06:54:08

2K+ Views

To flat a JavaScript array of objects into an object, we created a function that takes array of object as only argument. It returns a flattened object with key append by its index. The time complexity is O(mn) where n is the size of array and m is the number of properties in each object. However, its space complexity is O(n) where n is the size of actual array.Example//code to flatten array of objects into an object //example array of objects const notes = [{    title: 'Hello world',    id: 1 }, {    title: 'Grab a coffee',   ... Read More

Asynchronous Functions and the Node Event Loop in Javascript

sudhir sharma
Updated on 06-Aug-2020 07:54:48

167 Views

Asynchronous Functions, the programs continue to run. It does not wait! This way the waiting time of the user is reduced. Also, Javascript as a programming language itself is asynchronous.For example, if in code we are running an expensive request, which might require a lot of time, then in case of an asynchronous function, the waiting time would be too much, and the user wouldn’t be able to perform anything else too!Thus generally we prefer using asynchronous code when performing expensive and time-consuming operations.Let’s take an example of Anyncronous function in javascript −Exampleconsole.log('One'); jQuery.get('page.html', function (data) {    console.log("Two"); }); console.log('Three');OutputOne, ... Read More

Advertisements