Categories
JavaScript Answers

How to Create a Zero-Filled JavaScript Array?

We’ve to create a JavaScript array filled with all zeroes in our code.

In this article, we’ll look at how to create a zero-filed JavaScript array.

Array.prototype.fill

We can use the fill array method to fill all the entries of an array with the values we want.

For instance, we can write:

const arr = new Array(10).fill(0);  
console.log(arr);

The Array constructor takes the length of an array if we only pass one argument into it.

fill takes the value we want to fill the array with.

Then arr is [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] .

fill is available since ES6.

The apply and map Methods

We can also use the Array.apply method to create an empty array that we can use the map method with.

Then we pass in a callback that returns the value we want into the map method.

For instance, we can write:

const arr = Array.apply(undefined, Array(10)).map(() => 0);  
console.log(arr);

We call apply with Array(10) to create an array with 10 slots that we can fill with map .

Then in map , we just pass in a callback that returns 0 to fill all the entries with zeroes.

So we get the same result as the previous example.

Array.from

The Array.from method is an array static method that lets us return an array derived from another array.

So we can use it to map the values from one array to another, including an empty array.

For instance, we can write:

const arr = Array.from(Array(10), () => 0)  
console.log(arr);

We call Array.from with Array(10) to let us map the empty array with 10 slots to an array with stuff inside.

The 2nd argument is a callback that returns 0 so we fill all the entries with zeroes.

Therefore, we get the same result as before.

Another way to use Array.from is to pass in an object with the length property set to the array length we want.

To do this, we write:

const arr = Array.from({  
  length: 10  
}, () => 0)  
console.log(arr);

And we get the same result as before.

Conclusion

We can create a zero-filled array with JavaScript by using the fill method or the Array.from method.

Also, we can use the Array constructor to create an array.

Categories
JavaScript Answers

How to Access the First Property of a JavaScript Object?

In our JavaScript programs, sometimes we only want to access the first property of a JavaScript object.

In this article,e we’ll look at various ways we can access only the first property of a JavaScript object.

Object.keys

The Object.keys method returns an array with the string keys of an object.

So we can access the first property in an object by writing:

const obj = {
  a: 1,
  b: 2
};
const [prop] = Object.keys(obj)
console.log(obj[prop])

We have the obj object with some properties.

And we call Object.keys and destructure the first key from the returned array and assign it to prop .

And then we get the value of the first property returned with obj[prop] .

So we get 1 from the console log.

for-in Loop and break

We can use the for-in loop to loop through an object and break after the first iteration.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
};

for (const prop in obj) {
  console.log(obj[prop])
  break;
}

We have the for-in loop and log the first property value returned.

prop has the property key string.

Then we use break to stop iterating.

Object.values

We can use the Object.values method to get the values from an object.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
};

const [value] = Object.values(obj)
console.log(value)

If we just want the first property value, then we can just use Object.values and destructure it from the returned array.

Object.entries

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

For instance, we can write:

const obj = {
  a: 1,
  b: 2
};

const [
  [key, value]
] = Object.entries(obj)
console.log(key, value)

to get the first key-value pair from the returned array.

We just destructure it from the nested array.

And so key is 'a' and value is 1.

Conclusion

We can use JavaScript object static methods or the for-in loop to get the first property from a JavaScript object.

Categories
JavaScript Answers

How to Subtract Days from a JavaScript Date?

Subtract dates from a date is an operation that we’ve to do often in our JavaScript code.

In this article, we’ll look at how to subtract days from a JavaScript date.

Date.prototype.getDate and Date.prototype.setDate

We can use the getDate method to get the date.

And then use the setDate method to set the date by manipulating the date we got from getDate and passing the returned value into setDate .

For instance, we can write:

const date = new Date(2021, 1, 1);
date.setDate(date.getDate() - 5);
console.log(date)

to subtract 5 days from February 1, 2021.

We call getDate from the date object.

Then we subtract 5 days from it.

And then we pass that into setDate .

Therefore date is now 'Wed Jan 27 2021 00:00:00 GMT-0800 (Pacific Standard Time)’ .

date is changed in place with setDate .

Date.prototype.getTime and Date.prototype.setTime

We can also call setTime to set the timestamp of the date instead of the days.

This is more precise since the time is in milliseconds.

To do this, we write:

const dateOffset = (24 * 60 * 60 * 1000) * 5;
const date = new Date(2021, 1, 1);
date.setTime(date.getTime() - dateOffset);
console.log(date)

We have the dateOffset in milliseconds.

And we have the same date object as in the previous example.

In the 3rd line, we call setTime with the timestamp value returned from getTime , which is in milliseconds.

And we subtract that by dateOffset , which is 5 days in milliseconds.

date is changed in place with setTime .

So date in string form is now ‘Wed Jan 27 2021 00:00:00 GMT-0800 (Pacific Standard Time)' .

moment.js

We can use the moment.js library to make date manipulation easier.

For instance, we can write:

const dateMnsFive = moment('2021-02-01').subtract(5, 'day');
console.log(dateMnsFive.toDate())

We create a moment object for February 1, 2021 with moment .

The returned object has the subtract method to let us subtract the time amount we want.

The first argument is the amount.

And the 2nd argument is the unit of the amount to subtract from.

Then we can convert that back to a native JavaScript date object with toDate .

And so we get the same result as the previous examples.

Moment objects also come with the toISOString method.

For instance, we can write:

const dateMnsFive = moment('2021-02-01').subtract(5, 'day');
console.log(new Date(dateMnsFive.toISOString()))

We can pass in the string returned by toISOString to the Date constructor to get a native date object back.

And so we get the same result as the previous example.

Conclusion

We can subtract days from a date with native JavaScript date methods.

To make the work easier, we can also use a library like moment.js to help us.

Categories
JavaScript Answers

How to Get the User’s Time Zone and Offset in JavaScript?

Sometimes, we need to get the user’s time zone in our JavaScript web app.

In this article, we’ll look at how to get the user’s time zone and offset in JavaScript.

Date.prototype.getTimezoneOffset

JavaScript’s native Date objects has the getTimezoneOffset method that returns the user’s time zone.

To use it, we can write:

const offset = new Date().getTimezoneOffset();  
console.log(offset);

It returns the difference between UTC and local time.

So we see that offset is 480 if we’re in the Pacific Standard Time.

The offset is positive when it’s behind UTC and negative otherwise.

The offset is in minutes so we divide it by 60 to get the number of hours.

Daylight saving time prevents this value from being constant.

The Intl.DateTimeFormat Constructor

Also, we can use theIntl.DateTimeFormat().resolvedOptions().timeZone property to get the user’s time zone.

For instance, if we have:

console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)

Then if we’re in the Pacific Time Zone, we may get something like:

'America/Los_Angeles'

returned.

Extract the Time Zone from the Date String

We can extract the time zone from the string returned from the toString method from a JavaScript native Date instance.

For instance, we can write:

const split = new Date().toString().split(" ");  
const timeZone = split.slice(-3).join(' ')  
console.log(timeZone)

And timeZone should be ‘(Pacific Standard Time)’ if we’re in the Pacific Standard Time time zone.

We split the date string returned from toString by a space with split .

Then we call slice with -3 to get the last 3 parts of the string.

And we join them together with join .

To make the extract easier, we can use a regex object.

For instance, we can write:

const [timeZone] = new Date().toString().match(/([A-Z]+[+-][0-9]+.*)/)  
console.log(timeZone)

to get the part of the date string with the upper case letters, plus or minus sign, the digits, and the time zone name together.

We call match on it to get the match.

It returns an object, so we can destructure the result and assign it to timeZone .

And so timeZone is:

'GMT-0800 (Pacific Standard Time)'

We can extract the letters and digits part only by writing:

const [timeZone] = new Date().toString().match(/([A-Z]+[+-][0-9]+)/)  
console.log(timeZone)

And we get 'GMT-0800' for timeZone .

We can extract the text in parentheses with:

const [timeZone] = new Date().toString().match(/(([A-Za-zs].*))/)  
console.log(timeZone)

And timeZone would be ‘(Pacific Standard Time)‘.

Also, we can extract the hours’ difference from UTC by writing:

const [timeZone] = new Date().toString().match(/([-+][0-9]+)s/)  
console.log(timeZone)

And we get '-0800' if we’re in the Pacific Standard Time time zone.

Conclusion

We can get the user’s time zone in multiple ways with JavaScript.

We can extract the items from a date string or we can use a library to built-in methods to extract them.

Categories
JavaScript Answers

How to Convert a String to a Date Object in JavaScript?

Sometimes, we have a date string that we want to convert to a date object in JavaScript.

In this article, we’ll look at how to convert a date string to a date object in JavaScript.

Extract the Parts of the Date String and Pass Them to the Date Constructor

One way to create a JavaScript date object from a date string is to extract the date parts from the date string and pass them all into the Date constructor.

For instance, we can write:

const [year, month, day] = '2020-04-03'.split('-');
const date = new Date(year, month - 1, day);
console.log(date.toDateString());

We call split on the date string with '-' to split the date string by the dash.

Then we destructure the year , month , and day from the split string array.

Next, we pass all of that into the Date constructor.

We’ve to subtract 1 from month since the month’s value that the Date constructor accepts is from 0 to 11, where 0 is for January and 11 is for December.

Then we get ‘Fri Apr 03 2020’ from the toDateString method.

We can also massage a date into an ISO date string and pass that into the Date constructor.

For instance, we can write:

const st = "26.04.2020";
const pattern = /(d{2}).(d{2}).(d{4})/;
const date = new Date(st.replace(pattern, '$3-$2-$1'));
console.log(date)

We get the parts of the date string with the pattern regex object.

Then we call replace on the st string and move the parts with the $ placeholder.

d extract digits.

The number in the curly braces is the number of digits to extract.

$1 is the first extracted part, which is '26'

$2 is the 2nd extracted part, which is '04'

And $3 is the 3rd extracted part, which is '2020' .

The Date constructor will create a UTC date.

So we get that date in string form is 'Sat Apr 25 2020 17:00:00 GMT-0700 (Pacific Daylight Time)’ .

moment.js

We can pass in a date string into moment.js’ moment function to convert it into an object we can manipulate.

For instance, we can write:

const momentDate = moment("12-25-2020", "MM-DD-YYYY");

to create a moment date object with the date string format specified in the 2nd argument.

We can use the isValid method to check for a valid date:

const isValid = moment("abc").isValid()
console.log(isValid)

isValid should false since 'abc' isn’t a valid date.

And we can convert a moment date object to a native JavaScript Date instance with toDate :

const date = moment("12-25-2020", "MM-DD-YYYY").toDate();
console.log(date)

Conclusion

To convert a date string to a JavaScript date object, we can either extract the parts of the date string ourselves and put it into the Date constructor.

Or we can use a third-party library like moment.js to help us make the job easier.