Trending December 2023 # How To Get The Smallest Of Zero Or More Numbers In Javascript? # Suggested January 2024 # Top 14 Popular

You are reading the article How To Get The Smallest Of Zero Or More Numbers In Javascript? updated in December 2023 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 How To Get The Smallest Of Zero Or More Numbers In Javascript?

In this tutorial, we shall learn to find the smallest among numbers in JavaScript.

Let’s discuss the available methods one after the other

Using the Math.min() Method

Here, the Math.min() is a static function of the placeholder object Math. If no parameters, the result is -Infinity. If the parameters are numbers, the result is the smallest among them. If any one of the parameters is not a number, the method returns NaN. This is an ECMAScript1 feature.

Syntax

Following is the syntax of Math.min() method −

Math.min(a1, a2,…an)

Here, we need to give numbers as parameters.

Parameters

a1, a2,…an − the numbers.

Example

Here, Math.min() directly finds the smallest value.

var

m1

=

Math

.

min

(

0

,

7

,

20

,

0.8

)

;

document

.

getElementById

(

“firstId”

)

.

innerHTML

=

“The smallest “

+

m1

;

Using Array.min() and Math.min().apply()

Here, an array of numbers is the input. The Math.min() applies this array and gives us the smallest number.

Syntax

Following is the syntax to use Array.min() method and Array.min.apply() −

Array.min = function(array) { return Math.min.apply(Math, array); }; var minimum = Array.min(arr);

Here, an array of numbers has to be given as the input.

Parameters

arr − The array.

Example

Here, Array.min() takes the input array and Math.min() applies it and returns the output.

Array

.

min

=

function

(

array

)

{

return

Math

.

min

.

apply

(

Math

,

array

)

;

}

;

var

array

=

[

24

,

2

,

1

,

0

]

;

var

minimum

=

Array

.

min

(

array

)

;

document

.

getElementById

(

“result”

)

.

innerHTML

=

“The smallest : “

+

minimum

;

Using the Destructuring Assignment Syntax/Spread Operator

Using the spread operator … we can extract values from an array or object into different variables. We can use this method because the Math.min() method does not support a direct array as an input.

Syntax

Users can follow the syntax below.

Math.min(...[p, q, r]);

Here, the spread operator helps the Math.min() method to return the smallest value.

Parameters

p, q, r − The array of numbers

Example

Here, Math.min() with the spread operator directly evaluates our input and displays the output.

var

res

=

Math

.

min

(

[

21

,

2

,

3

,

2

,

0

,

23

]

)

;

document

.

getElementById

(

“result”

)

.

innerHTML

=

res

;

Using the for Loop

As we know, here we consider the first number in an array as the smallest. Then we compare the remaining numbers in the array with this. Finally, we get the smallest value.

Syntax

Users can follow the syntax below.

for (var i = 0; i<arr.length; i++) { if (arr[i] < arr[0]) { } }

Here, the for loop evaluates the array of numbers and compares all with the first number and returns the smallest.

Parameters

arr − The array

i − The array index

Example

Here, the general array elements compare logic in the loop, and the output is displayed.

const

numbers

=

[

11

,

4

,

9

,

0

,

2

]

;

let

min

=

numbers

[

0

]

;

for

(

let

i

=

0

;

i

<

numbers

.

length

;

i

++

)

{

if

(

numbers

[

i

]

<

min

)

{

min

=

numbers

[

i

]

;

}

}

document

.

getElementById

(

“result”

)

.

innerHTML

=

“The smallest is “

+

min

;

Using the Array.reduce() Method

Here, we give the input to a call-back function. This function iterates through the input and gives the smallest value.

Syntax

Here, two values are compared every time of an array iteration and the smallest value is returned at the end.

Parameters

r1, r2 − r1 is the accumulator, and r2 is the current value respectively. During array iteration, if the current value becomes smaller than the accumulator, the current value becomes the next accumulator.

Example

Here, our input is processed by reduce(), and Math.min() returns the result.

const

nums

=

[

6

,

7

,

0.3

]

;

document

.

getElementById

(

“numb”

)

.

innerHTML

=

nums

;

document

.

getElementById

(

“result”

)

.

innerHTML

=

“The smallest is “

+

res

;

Using the Array.sort() Method

In the Array sort method, we get the minimum value at the start of the array.

Syntax arr.sort()[0]

Here, arr is the array of numbers.

Example

Here, the JavaScript sort is done on the input array and the first value is returned.

const

srtArr

=

[

60

,

10

,

80

]

;

document

.

getElementById

(

“numb”

)

.

innerHTML

=

srtArr

const

res

=

srtArr

.

sort

(

)

[

0

]

document

.

getElementById

(

“result”

)

.

innerHTML

=

“Smallest is “

+

res

;

This tutorial helped us to learn about the six methods to find the smallest of all numbers given.

The Math.min() method does not accept an array of elements. The reduce array method, loop method, and array apply method is more logical.

Among all the methods that we learned, the spread operator method and default array sort method is simple to use and work well.

You're reading How To Get The Smallest Of Zero Or More Numbers In Javascript?

Algorithm To Get The Combinations Of All Items In Array Javascript

In this problem statement, our task is to get the combinations of all items in an array with the help of Javascript functionalities. So for doing this task we can use a recursive approach that iteratively adds items to a running list of combinations.

Understanding the problem statement

The problem statement is to write a function in Javascript that will help to find out the combinations of all the elements in an array and create a separate array to show these combinations. For example, if we have an array [ 1, 2 ] so the combinations of this array will be [ [ 1, 2 ], [ 2 ] ].

Logic for the given problem

To create a function to get all the possible combinations of items in an array in Javascript can be done using a recursive algorithm which will iteratively add items to a list of combinations. So first we will define an array and initialize it as empty. Inside the created function we will define another function to recurse the running list of combinations.

Algorithm

Step 1 − Declare a function called getCombinations which is using a parameter of array.

Step 2 − Declare a result array inside the function which will hold our final list of combinations.

Step 3 − Define another function called recurse which will take two arguments cur and rem, here cur is the running list of items and rem is the array of items we have left to add in the combinations.

Step 4 − And after this if there are no items left in the rem array we will push current into the result array because we have reached the required result.

Step 5 − Otherwise we will iterate every item in the rem array and recursively call a recursive function with a new cur array that will include the current item.

Step 6 − Call recurse initially with an empty cur array and the full array we want to generate combinations for.

Step 7 − Return the final result array which contains all possible combinations of the input array.

Code for the algorithm function getCombinations(array) { const result = []; function recurse(cur, rem) { if (rem.length === 0) { result.push(cur); } else { for (let i = 0; i < rem.length; i++) { recurse([...cur, rem[i]], rem.slice(i + 1)); } } } recurse([], array); return result; } const array = [10, 20, 30, 40]; const combinations = getCombinations(array); console.log(combinations); Complexity

The time complexity for the above created function is O(2^n) because the algorithm generates all possible combinations of items in the array and there are 2^n possible combinations. And the space complexity for the code is also O(2^n) because the algorithm generates a list of 2^n combinations.

Conclusion

The above code provides a simple solution to generate all possible combinations of items in an array in Javascript. So it has an O(2^n) time and space complexity which can make it less efficient for large arrays. So it is important to note the size of the array when deciding whether to use this algorithm.

How Do I Get The Current Date And Time In Javascript?

This tutorial teaches us to get the date and time in JavaScript. Nowadays, JavaScript is the most popular programming language used for user interaction with the browser. We can say that it is hard to find a single web application that does not use JavaScript.

The purpose of creating this tutorial is to make programmers familiar with the Date() object. Users can get today’s date and current time using the date class. While developing the applications, programmers maybe need to show the current date and time according to the user’s local zone, and we can fill this requirement using the date class. Also, sometimes we need to store the user’s session start and end times in our app database.

To solve all the problems, we just create an object of date class and use its various methods to get the current date and time in this tutorial.

Get Date and Time using the Date Object

Get date and time using the toLocaleString() Method

Get Date and Time using the Date Object

The Date class contains several methods; we can fetch the current date, day, and time by using them. Also, it includes hundreds of different methods that programmers can use according to their requirements.

Syntax

Users can follow the below syntax for different methods-

let newDate = new Date();

Using the below syntax users can get the year, month and date.

let year = newDate.getFullYear(); let month = newDate.getMonth(); let todaySDate = newDate.getDate()

Using the below syntax users can get hours, minutes, and second.

let hours = newDate.getHours(); let minutes = newDate().getMinutes();       let date = document.getElementById("date");       let time = document.getElementById("time");             let newDate = new Date();       let year = newDate.getFullYear();       let month = newDate.getMonth();       let todaySDate = newDate.getDate();       let hours = newDate.getHours();       let minutes = newDate.getMinutes();       let seconds = newDate.getSeconds();       date.innerHTML = " " + todaySDate + "/ " + month + "/ " + year;       time.innerHTML = hours + ": " + minutes + ": " + seconds; let dateAndTime = date.toLocaleString(); let date = date.toLocaleDateString(); let time = date.toLocaleTimeString();

Users can follow the below syntax, if they want to get date and time for any local region.

let options = {    year: ‘numeric’,    month: ‘long’,    day: ‘numeric’,    weekday: ‘long’, }       let dateAndTime = document.getElementById("dateAndTime");       let date = document.getElementById("date");       let time = document.getElementById("time");       let dateIN = document.getElementById("dateIN");       let dateUs = document.getElementById("dateUs");

            let newDate = new Date();       dateAndTime.innerHTML = newDate.toLocaleString();       date.innerHTML = newDate.toLocaleDateString();       time.innerHTML = newDate.toLocaleTimeString();

            var options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long', };       dateIN.innerHTML = newDate.toLocaleString("en-IN", options);       dateUs.innerHTML = newDate.toLocaleString("en-US", options);

Cookies In Javascript: Set, Get & Delete Example

What are Cookies?

A cookie is a piece of data that is stored on your computer to be accessed by your browser. You also might have enjoyed the benefits of cookies knowingly or unknowingly. Have you ever saved your Facebook password so that you do not have to type it each and every time you try to login? If yes, then you are using cookies. Cookies are saved as key/value pairs.

Why do you need a Cookie?

The communication between a web browser and server happens using a stateless protocol named HTTP. Stateless protocol treats each request independent. So, the server does not keep the data after sending it to the browser. But in many situations, the data will be required again. Here come cookies into a picture. With cookies, the web browser will not have to communicate with the server each time the data is required. Instead, it can be fetched directly from the computer.

Javascript Set Cookie

You can create cookies using document. cookie property like this.

document.cookie = "cookiename=cookievalue" document.cookie = "cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00 UTC"

You can also set the domain and path to specify to which domain and to which directories in the specific domain the cookie belongs to. By default, a cookie belongs to the page that sets the cookie.

document.cookie = "cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00 UTC; path=/ "

//create a cookie with a domain to the current page and path to the entire domain.

JavaScript get Cookie

You can access the cookie like this which will return all the cookies saved for the current domain.

var x = document.cookie JavaScript Delete Cookie

To delete a cookie, you just need to set the value of the cookie to empty and set the value of expires to a passed date.

Try this Example yourself:

Special instructions to make the code work … Press the run button twice

function createCookie(cookieName,cookieValue,daysToExpire) { var date = new Date(); date.setTime(date.getTime()+(daysToExpire*24*60*60*1000)); } function accessCookie(cookieName) { var name = cookieName + “=”; var allCookieArray = document.cookie.split(‘;’); for(var i=0; i<allCookieArray.length; i++) { var temp = allCookieArray[i].trim(); if (temp.indexOf(name)==0) return temp.substring(name.length,temp.length); } return “”; } function checkCookie() { var user = accessCookie(“testCookie”); if (user!=””) alert(“Welcome Back ” + user + “!!!”); else { user = prompt(“Please enter your name”); num = prompt(“How many days you want to store your name on your computer?”); if (user!=”” && user!=null) { createCookie(“testCookie”, user, num); } } }

How To Find The Name Of The First Form In A Document With Javascript?

Document.forms Syntax

The following syntax will show how we can use the forms property to access the name of the first form of the document using JavaScript.

let formName = document.forms[0].name;

In the above syntax, we used square brackets syntax to access the first element of the collection and then used the name property to get its name.

Steps

Step 1 − In the first step, we need to define two or more form tags in the document and then access all of them using the forms property of JavaScript.

Step 2 − In the next step, we will use the above syntax to get the name of the first form in the document.

Step 3 − In the third step, we will display the number of forms as well as the name of the first form in the document on the user screen using JavaScript.

Let us understand it practically with the help of a code example −

Example 1

The example below will illustrate the practical implementation of the forms property to find the name of the first form in the document using JavaScript −

let

formElem

=

document

.

forms

;

let

firstForm

=

formElem

[

0

]

.

name

;

“The name of first form in the document: “

+

firstForm

;

In the example above, we have used two forms named as formOne and formTwo in the document. We access a list of all forms present in the document inside form, that will be of type HTMLCollection.After that, we access the first element of the list using square brackets syntax to get the first form in the document and use the name property to get the name of the form inside firstForm.

Let us see what value the forms property will return if we have two nested forms in the document.

Approach

Step 1 − In this step, we will define the two forms one inside another such that nested forms and give them particular names.

Step 2 − In second step, we use the forms property to get the list of forms present in the document as we did in previous example.

Step 3 − In third step, we will access the name of the first form using the name property and display it on the user screen using JavaScript.

Example 2

Below example will show how the forms property will react in case of nested forms −

let

form

=

document

.

forms

;

let

firstForm

=

form

[

0

]

.

name

;

“The name of first form in the document: “

+

firstForm

;

In this example, we have seen that forms property consider the nested forms as single form and returns the name of the first form in the document whether it contain nested forms or not.

After reading this tutorial, one can able to find the name of the first form in the document using the forms property of JavaScript. We also learnt about a new data type HTMLCollection that is very much similar to the array data type in JavaScript and also about the reaction of the forms property in case we have nested forms in the document.

Implementation Of Linkedlist In Javascript

A linked list is a data structure that consists of a sequence of elements, each of which contains a reference (or “link”) to the next element in the sequence. The first element is called the head and the last element is called the tail.

Defining the Node Class and the LinkedList class

This is basically the prerequisite in order to implement a linked list in JavaScript. In this step, 2 classes namely one for the nodes and the other for the linked list need to be created.

The Node class represents a single node in the linked list. It has two properties which are data and next. The data property is used to store the actual data of the node, whereas the next property is a reference to the next node in the list. The Node class consists of a constructor that initializes the data and next property when creating a new Node.

class Node { constructor(data) { chúng tôi = data; chúng tôi = null; } }

The LinkedList class is a representation of the linked list itself. It has a head property that refers to the first node in the list. The LinkedList class also has a constructor that initializes the head property when creating a new LinkedList.

class LinkedList { constructor() { chúng tôi = null; chúng tôi = null; this.length = 0; } }

The LinkedList class also consists of a method that allows you to insert, delete, and search for nodes in the list while simultaneously allowing other operations like printing the list, counting the elements, reversing the list and so on.

Printing the linked list

You can print the elements of a linked list by traversing through the list and printing the data of each node.

printAll() { let current = this.head; while (current) { console.log(current.data); current = current.next; } } Adding Node to the Linked List

There are multiple methods to add data to a linked list depending on where the new node has to be inserted, and are as follows −

Adding node to the beginning of the linked list

To add node/ element at the start of a linked list, once a new node is created with the data, simply set its next property to the current head of the list. Then you can update the head of the list to the new node. This is also known as Insertion at the head of the linked list and is the most basic type of addition of data. It is simply done by calling the add function defined below.

add(data) { const newNode = new Node(data); if (!this.head) { chúng tôi = newNode; chúng tôi = newNode; } else { chúng tôi = newNode; chúng tôi = newNode; } this.length++; return this; } Adding node to the end of the linked list

To add node/ element at the end of a linked list, we need to traverse the list and find the last node. After which a new node with data is created and we set the next property of the last node to the new node. This is also known as Insertion at the tail of the linked list and is the second most basic type of addition of data. It is simply done by calling the addToTail function defined below.

addToTail(data) { let newNode = new Node(data); if (this.head === null) { chúng tôi = newNode; return; } let current = this.head; while (current.next !== null) { current = current.next; } chúng tôi = newNode; } Adding node at a specific position

To add node/ element at a specific position in a linked list, you can traverse the list to find the node at the position before the insertion point, create a new node with the data, set the next property of the new node to the current node at the position, and set the next property of the previous node to the new node.

addAtPosition(data, position) { let newNode = new Node(data); if (position === 1) { chúng tôi = this.head; chúng tôi = newNode; return; } let current = this.head; let i = 1; while (i < position - 1 && current) { current = current.next; i++; } if (current) { chúng tôi = current.next; chúng tôi = newNode; } } Example (Adding Nodes to the Linked List)

In the below example, we implement adding nodes at beginning, at end and at a specific position.

class Node { constructor(data) { chúng tôi = data; chúng tôi = null; } } class LinkedList { constructor() { chúng tôi = null; chúng tôi = null; this.length = 0; } add(data) { const newNode = new Node(data); if (!this.head) { chúng tôi = newNode; chúng tôi = newNode; } else { chúng tôi = newNode; chúng tôi = newNode; } this.length++; return this; } addToTail(data) { let newNode = new Node(data); if (this.head === null) { chúng tôi = newNode; return; } let current = this.head; while (current.next !== null) { current = current.next; } chúng tôi = newNode; } addAtPosition(data, position) { let newNode = new Node(data); if (position === 1) { chúng tôi = this.head; chúng tôi = newNode; return; } let current = this.head; let i = 1; while (i < position - 1 && current) { current = current.next; i++; } if (current) { chúng tôi = current.next; chúng tôi = newNode; } } it printAll() { let current = this.head; while (current) { console.log(current.data); current = current.next; } } } const list = new LinkedList(); list.add("node1"); list.add("node2"); list.add("node3"); list.add("node4"); console.log("Initial List:"); list.printAll(); list.addAtPosition("nodex",2); list.printAll(); list.addToTail("nodey"); list.printAll(); Output Initial List: node1 node2 node3 node4 List after adding nodex at position 2 node1 nodex node2 node3 node4 List after adding nodey to tail node1 nodex node2 node3 node4 nodey Removing Node

Removal of data too, can be done via several methods depending upon the requirement.

Removing a specific node

To remove a specific node from a linked list, we need to traverse the list and find the node before the one you want to remove, update its next property to skip over the node you want to remove, and update the reference to the next node. This removes the node based upon the value.

remove(data) { if (!this.head) { return null; } if (this.head.data === data) { chúng tôi = this.head.next; this.length--; return this; } let current = this.head; while (current.next) { if (current.next.data === data) { chúng tôi = current.next.next; this.length--; return this; } current = current.next; } return null; } Removing a node at a Specific Position

To remove a node at a specific position in a linked list, we need to traverse the list and find the node before the one you want to remove, update its next property to skip over the node you want to remove, and update the reference to the next node. This is basically removing the node based upon the index value of it.

removeAt(index) { if (index === 0) return this.remove(); let current = this.head; for (let i = 0; i < index - 1; i++) { current = current.next; } chúng tôi = current.next.next; this.length--; return this; } Example (Removing Nodes from the Lined List)

In the below example, we implement removing a specific node and a node at a specific position.

class Node { constructor(data) { chúng tôi = data; chúng tôi = null; } } class LinkedList { constructor() { chúng tôi = null; chúng tôi = null; this.length = 0; } add(data) { const newNode = new Node(data); if (!this.head) { chúng tôi = newNode; chúng tôi = newNode; } else { chúng tôi = newNode; chúng tôi = newNode; } this.length++; return this; } remove(data) { if (!this.head) { return null; } if (this.head.data === data) { chúng tôi = this.head.next; this.length--; return this; } let current = this.head; while (current.next) { if (current.next.data === data) { chúng tôi = current.next.next; this.length--; return this; } current = current.next; } return null; } removeAt(index) { if (index === 0) return this.remove(); let current = this.head; for (let i = 0; i < index - 1; i++) { current = current.next; } chúng tôi = current.next.next; this.length--; return this; } printAll() { let current = this.head; while (current) { console.log(current.data); current = current.next; } } } const list = new LinkedList(); list.add("node1"); list.add("node2"); list.add("node3"); list.add("node4"); console.log("Initial List:"); list.printAll(); list.remove("node2"); list.printAll(); list.removeAt(2); list.printAll(); Output Initial List: node1 node2 node3 node4 List after removing node2 node1 node3 node4 List after removing node at index 2 node1 node3 Conclusion

Implementing a linked list in JavaScript involves creating a Node class to represent each node in the list and a LinkedList class to represent the list itself, and adding methods to the LinkedList class to perform operations such as adding and removing data, and printing the list. It’s important to also consider edge cases and handle them accordingly in your implementation. There are several ways of adding or removing data from a LinkedList based upon the use case.

Update the detailed information about How To Get The Smallest Of Zero Or More Numbers In Javascript? on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!