Found 9313 Articles for Object Oriented Programming

Creating an associative array in JavaScript with push()?

AmitDiwan
Updated on 09-Sep-2020 13:20:18

1K+ Views

For this, use forEach() loop along with push(). Following is the code −Examplevar studentDetails= [    {       studentId:1,       studentName:"John"    },    {       studentId:1,       studentName:"David"    },    {       studentId:2,       studentName:"Bob"    },    {       studentId:2,       studentName:"Carol"    } ] studentObject={}; studentDetails.forEach (function (obj){    studentObject[obj.studentId] = studentObject[obj.studentId] || [];    studentObject[obj.studentId].push(obj.studentName); }); console.log(studentObject);To run the above program, you need to use the following command −node fileName.js.Here, my file name is demo116.js.OutputThis will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo116.js { '1': [ 'John', 'David' ], '2': [ 'Bob', 'Carol' ] }

Creating an associative array in JavaScript?

AmitDiwan
Updated on 09-Sep-2020 13:17:38

790 Views

You can create an associative array in JavaScript using an array of objects with key and value pair.Associative arrays are basically objects in JavaScript where indexes are replaced by user defined keys.Examplevar customerDetails= [    {       "customerId":"customer-1",       "customerName":"David",       "customerCountryName":"US"    },    {       "customerId":"customer-2",       "customerName":"Bob",       "customerCountryName":"UK"    },    {       "customerId":"customer-3",       "customerName":"Carol",       "customerCountryName":"AUS"    } ] for(var i=0;i node demo115.js David Bob Carol

How to display JavaScript array items one at a time in reverse on button click?

AmitDiwan
Updated on 09-Sep-2020 13:16:02

638 Views

Let’s say the following is our array −var listOfNames = [    'John',    'David',    'Bob' ];Following is our button −Click The Button To get the Reverse ValueNow, for array items in reverse, at first, reach the array length and decrement the length by 1. Then, print the contents of the particular index in reverse order.Example Live Demo Document Click The Button To get the Reverse Value    var listOfNames = [       'John',       'David',       'Bob'    ];    count=listOfNames.length-1;    function reverseTheArray(){       document.getElementById('reverseTheArray').innerHTML =       listOfNames[count];       count--;       if (count

Assign multiple variables to the same value in JavaScript?

AmitDiwan
Updated on 09-Sep-2020 13:10:44

3K+ Views

To assign multiple variables to the same value, the syntax is as followsvar anyVariableName1, anyVariableName2, anyVariableName3……….N; yourVariableName1=yourVariableName2=yourVariableName3=.........N=yourValue;Let’s say the following are our variables and we are assigning same value −var first, second, third, fourth, fifth; first=second=third=fourth=fifth=100;Examplevar first, second, third, fourth, fifth; first=second=third=fourth=fifth=100; console.log(first); console.log(second); console.log(third); console.log(fourth); console.log(fifth); console.log("The sum of all values="+(first+second+third+fourth+fifth));To run the above program, you need to use the following command −node fileName.js.Here, my file name is demo114.js.OutputThis will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo114.js 100 100 100 100 100 The sum of all values=500Read More

Creating a JavaScript Object from Single Array and Defining the Key Value?

AmitDiwan
Updated on 09-Sep-2020 13:09:40

98 Views

To convert a JavaScript object to key value, you need to use Object.entries() along with map(). Following is the code −Examplevar studentObject={    101: "John",    102: "David",    103: "Bob" } var studentDetails = Object.assign({}, studentObject) studentDetails = Object.entries(studentObject).map(([studentId,studentName])=>({studentId ,studentName})); console.log(studentDetails);To run the above program, you need to use the following command −node fileName.js.Here, my file name is demo113.js.OutputThis will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo113.js [    { studentId: '101', studentName: 'John' },    { studentId: '102', studentName: 'David' },    { studentId: '103', studentName: 'Bob' } ]

Formatting text to add new lines in JavaScript and form like a table?

AmitDiwan
Updated on 09-Sep-2020 13:08:23

276 Views

For this, use map() along with join(‘’).Then ‘’ is for new line. Following is the code −ExamplestudentDetails = [    [101, 'John', 'JavaScript'],    [102, 'Bob', 'MySQL'] ]; var studentFormat = '||Id||Name||subjName||'; var seperate = ''; seperate = seperate + studentDetails.map(obj => `|${obj.join('|')}|`).join(''); studentFormat = studentFormat + seperate; console.log(studentFormat);To run the above program, you need to use the following command −node fileName.js.Here, my file name is demo112.js.OutputThis will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo112.js ||Id||Name||subjName|| |101|John|JavaScript| |102|Bob|MySQL|

Create new array without impacting values from old array in JavaScript?

AmitDiwan
Updated on 09-Sep-2020 13:07:04

225 Views

Let’s say the following is our current array −var listOfNames=["John", "Mike", "Sam", "Carol"];Use JSON.parse(JSON.stringify()) to create new array and set values from the old array above.Examplefunction createNewArray(listOfNames) {    return JSON.parse(JSON.stringify(listOfNames)); } var listOfNames=["John", "Mike", "Sam", "Carol"]; var namesArray = listOfNames.slice(); console.log("The new Array="); console.log(namesArray);To run the above program, you need to use the following command −node fileName.js.Here, my file name is demo111.js.OutputThis will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo111.js The new Array= [ 'John', 'Mike', 'Sam', 'Carol' ]Read More

Display whether the office is closed or open right now on the basis of current time with JavaScript ternary operator

AmitDiwan
Updated on 09-Sep-2020 13:04:42

289 Views

Let’s say, we are matching the current date and time with the business hours. We need to display whether the office is closed or open right now on the basis of current time.Get the hours from the current date and can use the ternary operator for close and open. Following is the code −Example Live Demo Document    const gettingHours = new Date().getHours()    const actualHours = (gettingHours >= 10 && gettingHours < 18) ? 'Open' : 'Closed';    document.querySelector('.closeOrOpened').innerHTML = actualHours; To run the above program, save ... Read More

Counting elements of an array using a recursive function in JS?

AmitDiwan
Updated on 09-Sep-2020 13:02:23

497 Views

The recursive function calls itself with some base condition. Let’s say the following is our array with marks −var listOfMarks=[56, 78, 90, 94, 91, 82, 77];Following is the code to get the count of array elements −Examplefunction countNumberOfElementsUsingRecursive(listOfMarks) {    if (listOfMarks.length == 0) {       return 0;    }    return 1 +    countNumberOfElementsUsingRecursive(listOfMarks.slice(1)); } var listOfMarks=[56, 78, 90, 94, 91, 82, 77]; console.log("The array="); console.log(listOfMarks); var numberOfElements=countNumberOfElementsUsingRecursive(listOfMarks); console.log("The Number of elements = "+numberOfElements);To run the above program, you need to use the following command −node fileName.js.Here, my file name is demo110.js.OutputThis will produce the following ... Read More

Get Random value from a range of numbers in JavaScript?

AmitDiwan
Updated on 09-Sep-2020 13:00:42

185 Views

Let’s say, first, we will set the start and end range and call the function:console.log(getRandomValueBetweenTwoValues(400, 480))We have passed start value 400 and end value 480. Let’s get the random value with Math.random() in JavaScript −Examplefunction getRandomValueBetweenTwoValues(startRange, endRange) {    return Math.floor(Math.random() * (endRange - startRange + 1) + startRange); } console.log(getRandomValueBetweenTwoValues(400, 480))To run the above program, you need to use the following command −node fileName.js.Here, my file name is demo109.js.OutputThis will produce the following output −PS C:\Users\Amit\JavaScript-code> node demo109.js 401

Advertisements