Categories
JavaScript Answers

How to Programmatically Set the Value of a Select Element Using JavaScript?

Setting the value Property

One way to set the value of a select element is to set the value of the value property of a select element.

For instance, we can write the following HTML:

<select>
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="grape">Grape</option>
</select>

to create our select element with the options.

Then we can set the value property of the select element after selecting it with JavaScript by writing:

const select = document.querySelector('select')
select.value = 'orange'

We use querySelector to get the select element.

Then we just set the value property to the value of the value attribute of the option element that we want to pick to select a value.

Therefore, we should see that Orange is picked from the drop-down when we load the page.

Setting the selected Property of an Option Element to true

We can also set the selected property of an option element to true to set an option in the drop-down.

To do this, we write the following HTML:

<select>
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="grape">Grape</option>
</select>

Then we can get the options with the options property and set the selected property of an option by writing:

const select = document.querySelector('select')
select.options[1].selected = true

select.options has the options.

And we can access a choice by its index.

Then we cal set the selected property of it to true to pick it.

Since Orange is the 2nd option, it has index 1.

And so Orange is set as the selected choice in the dropdown.

Categories
JavaScript Answers

How to Initialize a JavaScript Date to Midnight?

Date.prototype.setHours

We can use the setHours method to set the hour of the date to midnight.

For instance, we can write:

const d = new Date();  
d.setHours(0, 0, 0, 0);  
console.log(d)

We call setHours with the hours, minutes, seconds, and milliseconds all set to 0 to set the date d to midnight of the same date as the original date d .

The change mutates the d object.

So we see that d is midnight of the current date from the console log.

To set a date to tomorrow’s midnight, we can write:

const d = new Date();  
d.setHours(24, 0, 0, 0);  
console.log(d)

The first argument, which is the hours argument, is 24 instead of 0.

And from the console log, we should see that the date is the next day midnight.

If we want to make a copy of the date, we can pas the date to the Date constructor:

const d = new Date(new Date().setHours(0, 0, 0, 0));  
console.log(d)

Date.prototype.setUTCHours

If we want to work with UTC times, we can use the setUTCHours method to set a time to midnight.

For instance, we can write:

const d = new Date();  
d.setUTCHours(0, 0, 0, 0);  
console.log(d)

to set a date to midnight UTC.

moment.js

The moment.js library lets us set a date to midnight with the startOf method.

For instance, we can write:

const d = moment().startOf('day');  
console.log(d)

We call startOf with 'day' to set the moment object’s date-time to midnight of the same date that the moment date is on.

Categories
JavaScript Answers

How to Get Distinct Values From an Array of Objects in JavaScript?

Using Array.prototype.map, Sets, and the Spread Operator

One way to get distinct values from an array of JavaScript objects is to use the array’s map method to get an array with the values of a property in each object.

Then we can remove the duplicate values with the Set constructor.

And then we can convert the set back to an array with the spread operator.

For instance, we can write:

const array = [{
    "name": "Joe",
    "age": 17
  },
  {
    "name": "Bob",
    "age": 17
  },
  {
    "name": "Carl",
    "age": 35
  }
]
const unique = [...new Set(array.map(item => item.age))];
console.log(unique)

We have the array array that has objects with the name and age properties.

And we want to get all the distinct values of the age property.

To do this, we call array.map with a callback that returns the age property value from each object and put them in the array.

Then we pass the returned array into the Set constructor.

And then we convert the set back to an array with the spread operator.

Therefore, unique is [17, 35] .

Using Array.prototype.map, Sets, and the Array.from

We can replace the spread operator with the Array.from method for converting the set to an array

For instance, we can write:

const array = [{
    "name": "Joe",
    "age": 17
  },
  {
    "name": "Bob",
    "age": 17
  },
  {
    "name": "Carl",
    "age": 35
  }
]
const unique = Array.from(new Set(array.map(item => item.age)));
console.log(unique)

to call Array.from with the set as the argument instead of the spread operator.

And we get the same result as before.

Using Array.prototype.map and Array.prototype.filter

Instead of using the Set constructor and the spread operator, we can also use the filter method to get the distinct values

For instance, we can write:

const array = [{
    "name": "Joe",
    "age": 17
  },
  {
    "name": "Bob",
    "age": 17
  },
  {
    "name": "Carl",
    "age": 35
  }
]
const unique = array
  .map(item => item.age)
  .filter((value, index, self) => self.indexOf(value) === index)

console.log(unique)

We call the filter method with a callback that has the value , index , and self parameters.

value has the value of the array returned from map .

index has the index of the element of the array returned from map that’s being iterated through.

And self is the array that’s returned by map .

And we return all the items that are the first instance of a given value with the indexOf method.

indexOf method returns the index of the first element of a value.

So we can use that to check against the index to only return the first item of each instance of each value.

And we get the same result as before.

Categories
JavaScript Answers

How to Add Hours to a JavaScript Date Object?

Date.prototype.getTime and Date.prototype.setTime

We can use the JavaScript native getTime method to get the timestamp of a date in milliseconds.

And we can use the setTime method to set the timestamp of a date in milliseconds.

Therefore, to add hours to an existing date, we can write:

const date = new Date(2021, 1, 1)
const h = 2
date.setTime(date.getTime() + (h * 60 * 60 * 1000))
console.log(date)

We have the date object that has a date that we want to add hours to.

h has the number of hours we want to add.

Then we call setTime with the timestamp of the new date in milliseconds.

We get the timestamp of date plus 2 hours by writing:

date.getTime() + (h * 60 * 60 * 1000)

(h * 60 * 60 * 1000) is 2 hours in milliseconds.

Then we get that date is:

Mon Feb 01 2021 02:00:00 GMT-0800 (Pacific Standard Time)

Date.prototype.getHours and Date.prototype.setHours

We can also use the getHours and setHours method to get and set the hours of a JavaScript date object respectively.

For instance, we can write:

const date = new Date(2021, 1, 1)
const h = 2
date.setHours(date.getHours() + h)
console.log(date)

Then we get the same result as in the previous example.

We may also want to make a copy of the original date object and then change the hours in the copied date object.

For instance, we can write:

const date = new Date(2021, 1, 1)
const h = 2
const copiedDate = new Date(date.getTime());
copiedDate.setHours(date.getHours() + h)
console.log(copiedDate)

We make a copy by passing the timestamp in milliseconds to the Date constructor as we did in the 3rd line.

getTime returns the timestamp in milliseconds.

Date.prototype.getUTCHours and Date.prototype.setUTCHours

We can also use the getUTCHours and setUTCHours method to get and set the hours of a JavaScript date object respectively.

getUTCHours returns the hour of the day in UTC.

setUTCHours sets the hour in UTC.

So we can write:

const date = new Date(2021, 1, 1)
const h = 2
date.setUTCHours(date.getUTCHours() + h)
console.log(date)

to add 2 hours to date .

Moment.js

We can also use moment.js to add hours to a date.

For instance, we can write:

const newDate = new moment(new Date(2021, 1, 1)).add(10, 'hours').toDate();
console.log(newDate)

to add 10 hours to the date we pass into the moment function.

We call add on it to add 10 hours.

The first argument is the quantity to add.

And the 2nd argument is the unit of the quantity to add.

toDate converts the returned moment object with the new date-time back to a native JavaScript date object.

And so newDate is:

Mon Feb 01 2021 10:00:00 GMT-0800 (Pacific Standard Time)

when seen from the console log.

Categories
JavaScript Answers

How to Get a Key in a JavaScript Object by its Value?

Object.keys and Array.prototype.find

We can use the Object.keys method to return an array of non-inherited string keys in an object.

And we can use the JavaScript array’s find method to return the first instance of something that meets the given condition in an array.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
}
const value = 2;
const key = Object.keys(object).find(key => object[key] === value);
console.log(key)

We have the object object that we want to search for the key in.

And value is the value of the key that we want to search for.

We get all the keys of object with Object.kets .

Then we call find with a callback that returns object[key] === value .

key is the object key being iterated through to find the key name for the given value .

Therefore, we should see that key is 'b' from the console log.

Object.keys and Array.prototype.filter

We can replace the find with filter and destructure the result from the array returned by filter .

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
}
const value = 2;
const [key] = Object.keys(object).filter(key => object[key] === value);
console.log(key)

And we get the same result for key as in the previous example.

Object.entries and Array.prototype.find

We can use the Object.entries method to return an array of arrays of key-value pairs of an object.

Therefore, we can use the returned array to find the key of the object with the given value.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
}
const value = 2;
const [key] = Object.entries(object).find(([, val]) => val === value);
console.log(key)

We call find with a callback that has the parameter with the val variable destrutured from the parameter.

val has the value of the in the key-value pair array.

So when we return val === value , we return the same boolean expression as the first example.

From the returned result of find , we can get the key of from the returned key-value pair by destructuring it.

And so we get the same value of key logged in the console log.