Categories
JavaScript Answers

How to Extract a Value of a Property as an Array From an Array of JavaScript Objects?

Extracting a property value from an array of JavaScript objects is something that we’ve to do often.

In this article, we’ll look at how to create an array from property values extracted from an array of JavaScript objects.

The Array map Method

The map method is available in a JavaScript array instance that lets us map one array to another.

This means we can use it to extract property from each object in the array and put the extracted values in its own array.

For instance, we can write:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = objArray.map(a => a.foo);

We have the objArray array with objects with the foo property.

Then we call map with a function to return the value of the foo property from each array element.

a is the array element being iterated through.

Therefore, result is [1, 2, 3] .

We can also write:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = objArray.map(({
  foo
}) => foo)

In the map callback, we destructure the a object with the parameter.

So we can just get foo and return it.

Lodash

We can also use Lodash methods to do the same thing.

We can use the pluck method to map an array of objects to an object with the property value of a given property from each object in the array.

For instance, we can write:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = _.pluck(objArray, 'foo');

In the last line, we pass in objArray , which is the object array.

And the second has the argument of the property we want to get from each object in the array.

Therefore, result should give us the same answer as in the previous examples.

Lodash also has a map method to let us do the same thing.

For instance, we write:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = _.map(objArray, 'foo');

The arguments are the same as the ones taken by pluck and it returns the same result.

The latest version of Lodash also comes with the property method which we can combine with the map method by writing:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = _.map(objArray, _.property('foo'));

property returns an accessor a given property name we pass into the method.

And the accessor is recognized by map and it’ll use the accessor to extract the property from each object in the array.

Therefore, we get the same result as the other examples.

Conclusion

We can use plain JavaScript or Lodash to extract the value of a property from each object in an array.

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.