Find Occurrences of Object Property Value in Array with JavaScript

AmitDiwan
Updated on 11-Sep-2020 08:16:49

136 Views

For this, use the concept of reduce(). Following is the code −Exampleconst subjectDetails = [    {       subjectId: '101',       subjectName: 'JavaScript'    },    {       subjectId: '102',       subjectName: 'Java'    },    {       subjectId: '103',       subjectName: 'JavaScript'    } ]; console.log([...subjectDetails.reduce((obj1, obj2) => {    if (obj1.has(obj2.subjectName)){       obj1.get(obj2.subjectName).frequency++;    } else {       obj1.set(obj2.subjectName, { subjectName: obj2.subjectName,       frequency: 1 });    }    return obj1; }, new Map()).values()]);To run the above program, you need ... Read More

Add and Remove Names on Button Click with JavaScript

AmitDiwan
Updated on 11-Sep-2020 08:14:55

3K+ Views

To create, use add() method, whereas to delete created and appended element, you can use remove(). Following is the code −Example Live Demo Document Add A New Name AddName    var givenName = document.querySelector('#name')    var btnClass = document.querySelector('#addNameButton')    var listOfName = document.querySelector('#listOfName')    btnClass.addEventListener('click', () => {       var actualName = givenName.value       if (actualName.length != 0) {          var createAnHTMLList = `${actualName}Remove Name`          listOfName.innerHTML += ... Read More

Remove Seconds and Milliseconds from Date and Convert to ISO String

AmitDiwan
Updated on 11-Sep-2020 08:10:43

3K+ Views

Let’s get the current date first −var currentDate = new Date(); console.log("The current date is as follows="+currentDate);Now, let us remove seconds/ milliseconds by setting them to 0 using setSeconds() −currentDate.setSeconds(0, 0);Convert to ISO String using toISOString() −currentDate.toISOString()Let us now see the complete code with output −Examplevar currentDate = new Date(); console.log("The current date is as follows="+currentDate); currentDate.setSeconds(0, 0); console.log("After removing seconds from date, the new date is as follows="); console.log(currentDate.toISOString());To run the above program, you need to use the following command −node fileName.js.Here, my file name is demo143.js.OutputThis will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo143.js The current date ... Read More

Toggle Hide Class Only on Selected Div with JavaScript

AmitDiwan
Updated on 11-Sep-2020 08:03:14

528 Views

To toggle hide class only on selected div, you need to set event on click button. Let’s say you need to hide a specific div on the click of + sign.To get font + or - icon, you need to link font-awesome −Following is the code to toggle hide class on clicking + sign −Example Live Demo Document .hideDiv { display: none; } Customer 1 John US Customer 2 David AUS $(".fa-plus").on("click", function(){ $(this).parent().siblings('.secondDetails').toggleClass("hideDiv"); }); To run ... Read More

Parse Float with Two Decimal Places in JavaScript

AmitDiwan
Updated on 11-Sep-2020 07:07:48

603 Views

To parse float with two decimal places, use the concept of toFixed(2). Following is the code −Examplevar price = 178932.89; var tax = 7.9; var totalPrice = price*tax; console.log("The actual value="+totalPrice); var gettingTwoPlacedValues = parseFloat(totalPrice).toFixed(2); console.log("After getting two placed values="+gettingTwoPlacedValues);To run the above program, you need to use the following command −node fileName.js.OutputHere, my file name is demo142.js. This will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo142.js The actual value=1413569.8310000002 After getting two placed values=1413569.83

Simplest Code for Array Intersection in JavaScript

AmitDiwan
Updated on 11-Sep-2020 07:04:27

175 Views

Let’s say the following are our arrays −var firstNamesArray=["John", "David", "Bob", "Sam", "Carol"]; var secondNamesArray=["Mike", "Carol", "Adam", "David"];The easiest way to perform array intersection is by using filter() along with includes(). Following is the code −Examplevar firstNamesArray=["John", "David", "Bob", "Sam", "Carol"]; var secondNamesArray=["Mike", "Carol", "Adam", "David"]; var intersectionOfArray=[]; intersectionOfArray=firstNamesArray.filter(v => secondNamesArray.includes(v)); console.log("Intersection of two array="); console.log(intersectionOfArray);To run the above program, you need to use the following command −node fileName.js.Here, my file name is demo141.js.OutputThis will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo141.js Intersection of two array= [ 'David', 'Carol' ]Read More

Update JavaScript Object with Existing Keys from Another Object

AmitDiwan
Updated on 11-Sep-2020 07:02:32

935 Views

For this, use hasOwnProperty(). Following is the code −Examplevar markDetails1 ={    'marks1': 78,    'marks2': 65 }; var markDetails2 ={    'marks2': 89,    'marks3': 90 } function updateJavaScriptObject(details1, details2) {    const outputObject = {};    Object.keys(details1)    .forEach(obj => outputObject[obj] =    (details2.hasOwnProperty(obj) ? details2[obj] : details1[obj]));    return outputObject; } console.log(updateJavaScriptObject(markDetails1, markDetails2));To run the above program, you need to use the following command −node fileName.js.Here, my file name is demo140.js.OutputThis will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo140.js { marks1: 78, marks2: 89 }

Split String When Value Changes in JavaScript

AmitDiwan
Updated on 11-Sep-2020 06:52:03

208 Views

For this, you can use match() along with regular expression. Following is the code −Examplevar originalString="JJJJOHHHHNNNSSSMMMIIITTTTHHH"; var regularExpression=/(.)\1*/g; console.log("The original string="+originalString); var splitting=originalString.match(regularExpression); console.log("After splitting the original string="); console.log(splitting);To run the above program, you need to use the following command −node fileName.js.Here, my file name is demo139.js.OutputThis will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo139.js The original string=JJJJOHHHHNNNSSSMMMIIITTTTHHH After splitting the original string=[    'JJJJ', 'O',    'HHHH', 'NNN',    'SSS', 'MMM',    'III', 'TTTT',    'HHH' ]

Find Second Largest Element in JavaScript Array

AmitDiwan
Updated on 11-Sep-2020 06:50:14

553 Views

Let’s say following is our array −var numbers=[10,50,80,60,89];To find the second largest element, the code is as follows −Examplevar numbers=[10,50,80,60,89]; var firstLargerNumber = Number.MIN_SAFE_INTEGER; var secondlargerNumber = firstLargerNumber; for(var tempNumber of numbers){    if(tempNumber > firstLargerNumber){       secondlargerNumber = firstLargerNumber;       firstLargerNumber = tempNumber;    }    else if(tempNumber > secondlargerNumber){       secondlargerNumber = tempNumber;    } } console.log("The second largest number="+secondlargerNumber);To run the above program, you need to use the following command −node fileName.js.Here, my file name is demo138.js.OutputThis will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo138.js The second largest number=80

Trigger Button Click and Generate Alert on Form Submission in JavaScript

AmitDiwan
Updated on 11-Sep-2020 06:47:17

11K+ Views

Let’s say the following is our button −SubmitOn the basis of button id, on form submission, generate an alert −$("#submitForm").click(function() {    alert("The Form has been Submitted."); });Example Live Demo Document CollegeId= CollegeName=  Submit    $("#submitForm").click(function() {       alert("The Form has been Submitted.");    }); To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.OutputThis will produce the following output −After clicking the button, you can see the following output −

Advertisements