Javascript Articles

Page 441 of 534

Why does Array.map(Number) convert empty spaces to zeros? JavaScript

AmitDiwan
AmitDiwan
Updated on 18-Aug-2020 452 Views

Let’s say we are given the following code and output and we need to figure out why JavaScript converts empty strings(“ “) to 0 −const digify = (str) => {    const parsedStr = [...str].map(Number)    return parsedStr; } console.log(digify("778 858 7577"))Output[ 7, 7, 8, 0, 8, 5, 8, 0, 7, 5, 7, 7 ]This behaviour can be very disturbing especially when we have some 0 in the string as wellThis actually happens because inside of the map() function when we are converting each character to its numerical equivalent using Number, what it does is it actually uses Abstract Equality ...

Read More

How to set attribute in loop from array JavaScript?

AmitDiwan
AmitDiwan
Updated on 18-Aug-2020 1K+ Views

Let’s say we are required to write a function that takes in an array and changes the id attribute of first n divs present in a particular DOM according to corresponding values of this array, where n is the length of the array.We will first select all divs present in our DOM, iterate over the array we accepted as one and only argument and assign the corresponding id to each div −The code for doing the same is −const array = ['navbar', 'sidebar', 'section1', 'section2', 'footer']; const changeDivId = (arr) => {    const divsArray = document.querySelectorAll('div');    arr.forEach((element, index) ...

Read More

Get filename from string path in JavaScript?

AmitDiwan
AmitDiwan
Updated on 18-Aug-2020 2K+ Views

We need to write a function that takes in a string file path and returns the filename. Filename usually lives right at the very end of any path, although we can solve this problem using regex but there exists a simpler one-line solution to it using the string split() method of JavaScript and we will use the same here.Let’s say our file path is −"/app/base/controllers/filename.jsFollowing is the code to get file name from string path −Exampleconst filePath = "/app/base/controllers/filename.js"; const extractFilename = (path) => {    const pathArray = path.split("/");    const lastIndex = pathArray.length - 1;    return pathArray[lastIndex]; ...

Read More

How to convert array to object in JavaScript

AmitDiwan
AmitDiwan
Updated on 18-Aug-2020 426 Views

Let’s say we need to convert the following array of array into array of objects with keys as English alphabetconst data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];This can be done by mapping over the actual arrays and reducing the subarrays into objects like the below example −Exampleconst data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]; const dataArr = data.map(arr => { return arr.reduce((acc, cur, index) => ({    ...acc,       [String.fromCharCode(97 + index)]: cur    }), Object.create({})) }); console.log(dataArr);OutputThe console output for this code will be −[    { a: 1, b: 2, c: 3, d: 4 },    { a: 5, b: 6, c: 7, d: 8 },    { a: 9, b: 10, c: 11, d: 12 } ]

Read More

Replace() with Split() in JavaScript to append 0 if number after comma is a single digit

AmitDiwan
AmitDiwan
Updated on 18-Aug-2020 330 Views

Let’s say our sample string is −const a = "250,5";If the number after “,” is a single digit we have to append a 0 to it,If the string contains more than one ‘,’, we have to return -1This can be done simply by combining the split() and replace() functions like this as in the below example −Exampleconst a = "250,5"; const roundString = (str) => {    if(str.split(",").length > 2){       return -1;    }    return a.replace(`,${a.split(",")[1]}`, `,${a.split(",")[1]}0`);; } console.log(roundString(a));OutputThe console output for this code will be −250,50

Read More

Join every element of an array with a specific character using for loop in JavaScript

AmitDiwan
AmitDiwan
Updated on 18-Aug-2020 310 Views

Here we are supposed to write a function that takes in two arguments, first an array of String or Number literals, second a String and we have to return a string that contains all the elements of the array prepended and appended by the string.For example −applyText([1, 2, 3, 4], ‘a’);should return ‘a1a2a3a4a’For these requirements, the array map() method is a better option than the for loop and the code for doing so will be −Exampleconst numbers = [1, 2, 3, 4]; const word = 'a'; const applyText = (arr, text) => {    const appliedString = arr.map(element => { ...

Read More

Stop making form to reload a page in JavaScript

AmitDiwan
AmitDiwan
Updated on 18-Aug-2020 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
AmitDiwan
Updated on 18-Aug-2020 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

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

AmitDiwan
AmitDiwan
Updated on 18-Aug-2020 207 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
AmitDiwan
Updated on 18-Aug-2020 411 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
Showing 4401–4410 of 5,338 articles
« Prev 1 439 440 441 442 443 534 Next »
Advertisements