Found 6710 Articles for Javascript

Merge object properties through unique field then print data - JavaScript

AmitDiwan
Updated on 18-Aug-2020 07:36:56

147 Views

Let’s say we have a students object containing two properties names and marks. The names is an array of object with each object having two properties name and roll, similarly marks is an array of object with each object having properties mark and roll. Our task is to combine the marks and names properties according to the appropriate roll property of each object.The students object is given here −const students = {    marks: [{       roll: 123,       mark: 89    }, {       roll: 143,       mark: 69    }, ... Read More

How to print star pattern in JavaScript in a very simple manner?

AmitDiwan
Updated on 18-Aug-2020 07:32:48

1K+ Views

Here is a simple star pattern that we are required to print inside the JavaScript console. Note that it has to be printed inside the console and not in the output or HTML window −* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *Here’s the code for doing so in JavaScript −Exampleconst star = "* "; //where length is no of stars in longest streak const length = 6; for(let i = 1; i

JavaScript : Why does % operator work on strings? - (Type Coercion)

AmitDiwan
Updated on 18-Aug-2020 07:29:27

355 Views

Let’s say we have a code snippet here that produces some startling results. Firstly, we see that the modulo operator is working fine with strings as well (surprisingly). Secondly, concatenation of two strings produces awkward results.We need to explain why JavaScript does so?Here’s the problem code −Exampleconst numStr = '127'; const result = numStr % 5; const firstName = 'Armaan'; const lastName = 'Malik'; const fullName = firstName + + lastName; console.log('modulo result: ', result); console.log('full name: ', fullName);Outputmodulo result: 2 full name: ArmaanNaNBefore jumping into the code, let’s first learn a bit about one of the most fundamental topics ... Read More

Fix Problem with .sort() method in JavaScript, two arrays sort instead of only one

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

248 Views

One property of the Array.prototype.sort() function is that it is an inplace sorting algorithm, which means it does not create a new copy of the array to be sorted, it sorts the array without using any extra space, making it more efficient and performant. But this characteristic sometimes leads to an awkward situation.Let’s understand this with an example. Assume, we have a names array with some string literals We want to keep the order of this array intact and want another array containing the same elements as the names array but sorted alphabetically.We can do something like this −const names ... Read More

What is this problem in JavaScript’s selfexecuting anonymous function?

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

168 Views

Let’s say here is a sample code snippet and we are required to tell the possible output for this snippet and provide an explanation for itvar name = 'Zakir'; (() => {    name = 'Rahul';    return;    console.log(name);    function name(){       let lastName = 'Singh';    } })(); console.log(name);Let’s go through this problem line by line with a naive approach1 → ‘Zakir’ stored in variable name3 → We enter inside a self-executing anonymous function4 → The variable name is reinitialized to ‘Rahul’5 → return statement is encountered, so we exit the function15 → print the ... Read More

Strange syntax, what does `?.` 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 - JavaScript

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

461 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

How to create a function which returns only even numbers in 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 of 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

Advertisements