Strange Syntax: What Does It Mean in JavaScript

AmitDiwan
Updated on 18-Aug-2020 07:26:17

1K+ Views

Let’s try to understand ‘?.’ with an example.Consider the following object example describing a male human being of age 23 −const being = {    human: {       male: {          age: 23       }    } };Now let’s say we want to access the age property of this being object. Pretty simple, right? We will just use chaining to access like the below code −Exampleconst being = {    human: {       male: {          age: 23       }    } }; console.log(being.human.male.age);OutputConsole output is ... Read More

Combine Unique Items of an Array of Arrays While Summing Values in JavaScript

AmitDiwan
Updated on 18-Aug-2020 07:25:12

458 Views

We have an array of array, each subarray contains exactly two elements, first is a string, a person name in this case and second is a integer, what we are required to do is combine all those subarrays that have their first element same and the second element should be a sum of the second elements of the common subarrays.Following is our example array −const example = [[    'first',    12 ], [    'second',    19 ], [    'first',    7 ]];Should be converted to the followingconst example = [[    'first',    19    ], [ ... Read More

Reverse a Number in JavaScript

AmitDiwan
Updated on 18-Aug-2020 07:23:26

7K+ Views

Our aim is to write a JavaScript function that takes in a number and returns its reversed numberFor example, reverse of 678 −876Here’s the code to reverse a number in JavaScript −Exampleconst num = 124323; const reverse = (num) => parseInt(String(num) .split("") .reverse() .join(""), 10); console.log(reverse(num));OutputOutput in the console will be −323421ExplanationLet’s say num = 123We convert the num to string → num becomes ‘123’We split ‘123’ → it becomes [‘1’, ‘2’, ‘3’]We reverse the array → it becomes [‘3’, ‘2’, ‘1’]We join the array to form a string → it becomes ‘321’Lastly we parse the string into a Int and returns it → 321

Return Only Even Numbers from JavaScript Array

AmitDiwan
Updated on 18-Aug-2020 07:22:21

1K+ Views

Here, we need to write a function that takes one argument, which is an array of numbers, and returns an array that contains only the numbers from the input array that are even.So, let's name the function as returnEvenArray, the code for the function will be −Exampleconst arr = [3,5,6,7,8,4,2,1,66,77]; const returnEvenArray = (arr) => {    return arr.filter(el => {       return el % 2 === 0;    }) }; console.log(returnEvenArray(arr));We just returned a filtered array that only contains elements that are multiples of 2.OutputOutput in the console will be −[ 6, 8, 4, 2, 66 ]Above, we returned only even numbers as output.

Filtering JavaScript Object

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

241 Views

Here we need to create a function that takes in an object and a search string and filters the object keys that start with the search string and returns the objectHere is the code for doing so −Exampleconst obj = {    "PHY": "Physics",    "MAT": "Mathematics",    "BIO": "Biology",    "COM": "Computer Science",    "SST": "Social Studies",    "SAN": "Sanskrit",    "ENG": "English",    "HIN": "Hindi",    "ESP": "Spanish",    "BST": "Business Studies",    "ECO": "Economics",    "CHE": "Chemistry",    "HIS": "History" } const str = 'en'; const returnFilteredObject = (obj, str) => {    const filteredObj = {}; ... Read More

Display Array Items on a Div Element Using Vanilla JavaScript

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

4K+ Views

To embed the elements of an array inside a div, we just need to iterate over the array and keep appending the element to the divThis can be done like this −Exampleconst myArray = ["stone", "paper", "scissors"]; const embedElements = () => {    myArray.forEach(element => {       document.getElementById('result').innerHTML +=       `${element}`;       // here result is the id of the div present in the DOM    }); };This code makes the assumption that the div in which we want to display the elements of array has an id ‘result’.The complete code for this ... Read More

Combine Objects and Delete a Property with JavaScript

AmitDiwan
Updated on 18-Aug-2020 07:17:45

222 Views

We have the following array of objects that contains two objects and we are required to combine both objects into one and get rid of the chk property altogether −const err = [    {       "chk" : true,       "name": "test"    },    {       "chk" :true,       "post": "test"    } ];Step 1 − Combining objects to form a single objectconst errObj = Object.assign(...err);Step 2 − Removing the chk propertydelete errObj['chk']; console.log(errObj);Let us now see the entire code with output −Exampleconst err = [    {       ... Read More

Clearing LocalStorage in JavaScript

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

488 Views

There exists two ways actually to clear the localStorage via JavaScript.Way1 − Using the clear() methodlocalStorage.clear();Way2 − Iterating over localStorage and deleting all keyfor(key in localStorage){ delete localStorage[key]; }Both ways will work.Example if (typeof(Storage) !== "undefined") {    localStorage.setItem("product", "Tutorix");    // cleared before displaying    localStorage.clear();    document.getElementById("storage").innerHTML = localStorage.getItem("product"); } else {    document.getElementById("storage").innerHTML = "Sorry, no Web Storage    compatibility..."; }

Why Does Array Map Convert Empty Spaces to Zeros in JavaScript

AmitDiwan
Updated on 18-Aug-2020 07:14:05

400 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

Set Attribute in Loop from Array in JavaScript

AmitDiwan
Updated on 18-Aug-2020 07:12:47

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

Advertisements