Found 9150 Articles for Object Oriented Programming

How to get sequence number in loops with JavaScript?

AmitDiwan
Updated on 12-Sep-2020 07:46:59

973 Views

To get sequence number in loops, use the forEach() loop. Following is the code −Examplelet studentDetails = [    {       id: 101, details: [{name: 'John'}, {name: 'David'},{name: 'Bob'}]},       {id:102, details: [{name:'Carol'},{name:'David'},       {name:'Mike'}]    } ]; var counter = 1; studentDetails.forEach(function(k){    k.details.forEach(function(f) {          console.log(counter++);       }    ); });To run the above program, you need to use the following command −node fileName.js.OutputHere, my file name is demo159.js. This will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo159.js 1 2 3 4 5 6

The best way to remove duplicates from an array of objects in JavaScript?

AmitDiwan
Updated on 12-Sep-2020 07:44:33

218 Views

Let’s say the following is our array of objects with duplicates −var studentDetails=[    {studentId:101},    {studentId:104},    {studentId:106},    {studentId:104},    {studentId:110},    {studentId:106}, ]Use the concept of set to remove duplicates as in the below code −Examplevar studentDetails=[    {studentId:101},    {studentId:104},    {studentId:106},    {studentId:104},    {studentId:110},    {studentId:106}, ] const distinctValues = new Set const withoutDuplicate = [] for (const tempObj of studentDetails) {    if (!distinctValues.has(tempObj.studentId)) {       distinctValues.add(tempObj.studentId)       withoutDuplicate.push(tempObj)    } } console.log(withoutDuplicate);To run the above program, you need to use the following command −node fileName.js.OutputHere, my file name ... Read More

Appending a key value pair to an array of dictionary based on a condition in JavaScript?

AmitDiwan
Updated on 12-Sep-2020 07:42:51

1K+ Views

For this, use Object.assign(). Following is the code −Exampleconst details = {john:{'studentName':'John'}, david:{'studentName':'David'}, mike:{'studen tName':'Mike'}, bob:{'studentName':'Bob'}, carol:{'studentName':'Carol'}}, join_values = ['David', 'Carol'],    output = Object.assign(       {},       ...Object       .keys(details)       .map(key =>       ({[key]: {          ...details[key],          lastName: join_values.includes(details[key].studentName) ?          'Miller' : 'Smith'    }}))) console.log(output)To run the above program, you need to use the following command −node fileName.js.OutputHere, my file name is demo157.js. This will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo157.js {    john: ... Read More

Create increment decrement plus minus buttons programmatically for HTML input type number in JavaScript

AmitDiwan
Updated on 12-Sep-2020 07:39:10

16K+ Views

We will be creating two buttons, one for Increment and another Decrement −On clicking Increment (+), user will be able to increment the number in input type numberOn clicking Decrement (-), user will be able to decrement the number in input type numberExample Live Demo Document + -    function increment() {       document.getElementById('demoInput').stepUp();    }    function decrement() {       document.getElementById('demoInput').stepDown();    } To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option ... Read More

How to remove the first character of link (anchor text) in JavaScript?

AmitDiwan
Updated on 12-Sep-2020 07:36:11

414 Views

Here, we have set “Aabout_us” and “Hhome_page” with incorrectly spellings as anchor text.You can use substring(1) along with innerHTML to remove the first character and display them correctly as “about_us” and “home_page” respectively.Example Live Demo Document Aabout_us Hhome_page    [...document.querySelectorAll('.linkDemo div a')].forEach(obj=>    obj.innerHTML=obj.innerHTML.substring(1)) 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 with the correct forms ... Read More

How to know if two arrays have the same values in JavaScript?

AmitDiwan
Updated on 12-Sep-2020 07:30:28

347 Views

Let’s say the following are our arrays −var firstArray=[100, 200, 400]; var secondArray=[400, 100, 200];You can sort both the arrays using the sort() method and use for loop to compare each value as in the below code −Examplevar firstArray=[100, 200, 400]; var secondArray=[400, 100, 200]; function areBothArraysEqual(firstArray, secondArray) {    if (!Array.isArray(firstArray) || ! Array.isArray(secondArray) ||    firstArray.length !== secondArray.length)    return false;    var tempFirstArray = firstArray.concat().sort();    var tempSecondArray = secondArray.concat().sort();    for (var i = 0; i < tempFirstArray.length; i++) {       if (tempFirstArray[i] !== tempSecondArray[i])          return false;    }   ... Read More

How to access nested JSON property based on another property's value in JavaScript?

AmitDiwan
Updated on 12-Sep-2020 07:29:03

511 Views

To access nested JSON property based on another property’s value, the code is as follows −Examplevar actualJSONData = JSON.parse(studentDetails()), studentMarks = getMarksUsingSubjectName(actualJSONData, "JavaScript"); console.log("The student marks="+studentMarks); function getMarksUsingSubjectName(actualJSONData, givenSubjectName){    for(var tempObj of actualJSONData){       if(tempObj.subjectName = givenSubjectName){          return tempObj.marks;       }    } } function studentDetails(){    return JSON.stringify(       [          { firstName : "John", subjectName: "JavaScript", marks : 97 },          { firstName : "David", subjectName: "Java", marks : 98 }       ]    ); }To run the above ... Read More

Replace array value from a specific position in JavaScript

AmitDiwan
Updated on 12-Sep-2020 07:26:43

532 Views

To replace value from a specific position, use splice() in JavaScript. Following is the code −Examplevar changePosition = 2 var listOfNames = ['John', 'David', 'Mike', 'Sam','Carol'] console.log("Before replacing="); console.log(listOfNames); var name = 'Adam' var result = listOfNames.splice(changePosition, 1, name) console.log("After replacing="); console.log(listOfNames)To run the above program, you need to use the following command −node fileName.js.OutputHere, my file name is demo14.js. This will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo154.js Before replacing= [ 'John', 'David', 'Mike', 'Sam', 'Carol' ] After replacing= [ 'John', 'David', 'Adam', 'Sam', 'Carol' ]

JavaScript Recursion finding the smallest number?

AmitDiwan
Updated on 11-Sep-2020 08:41:17

247 Views

Let’s say the following is our array −var numbers=[10,101,76,56,5,210,3,100];To find the smallest number, the code is as follows −Examplefunction findMinimumElementUsingRecursive(numbers) {    if (numbers.length==1){       return numbers[0];    }    else if(numbers[0]>numbers[1]) {       return findMinimumElementUsingRecursive(numbers.slice(1));    } else {       return       findMinimumElementUsingRecursive([numbers[0]].concat(numbers.slice(2)));    } } var numbers=[10,101,76,56,5,210,3,100]; console.log("The minimum element is="+findMinimumElementUsingRecursive(numbers));To run the above program, you need to use the following command −node fileName.js.OutputHere, my file name is demo152.js. This will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo152.js The minimum element is=3

JavaScript filter array by multiple strings

AmitDiwan
Updated on 29-Nov-2024 19:11:57

996 Views

Filtering an array by multiple strings in JavaScript involves identifying elements that match any string from a given list. This is commonly used in search filters, dynamic matching, or data processing tasks. JavaScript provides simple tools like the filter method and techniques such as includes for exact matches or regular expressions for pattern-based matching. These approaches help efficiently narrow down arrays based on specific criteria. Approaches to filter array by multiple strings Here are the following approaches to filter an array by multiple strings in JavaScript using regex (case-sensitive) and filter with includes: Using Regular Expressions ... Read More

Advertisements