Categories
JavaScript Answers

How to Use JavaScript Array Map Method with Objects Instead of Arrays?

Sometimes, we want to map object property values of an object to new values instead of mapping array values.

In this article, we’ll look at how to use JavaScript array’s map method with object instead of arrays.

Object.keys

The object.keys method returns an array of a JavaScript object’s string keys.

Therefore, we can loop through the keys to map the property values to their new values.

For instance, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
};
for (const key of Object.keys(obj)) {
  obj[key] *= 2
}
console.log(obj)

We have the obj object that has 3 properties in it.

Then we use Object.keys with obj to return the keys.

And then we use the for-of loop to loop through the keys.

Then we can use that to do what we want.

In this example, we multiple each property value by 2.

Therefore, obj is now:

{a: 2, b: 4, c: 6}

Object.keys and reduce

We can also combine the Object.keys method with the reduce method to map the values of properties if an object to new values.

For instance, we can write:

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

const newObj = Object.keys(obj).reduce((result, key) => {
  result[key] = obj[key] * 2
  return result
}, {})
console.log(newObj)

We call reduce on the string keys array returned by Object.keys .

The reduce callback has the result object which is the object that we have so far.

key has the string key value.

Then we get result[key] with the value we want.

We get the obj[key] value and multiply it by 2.

Then we return the result value.

The 2nd argument is set to an object so that the initial value of result is an object.

This way, we can put property values in them.

Therefore, newObj has the same value as the previous example.

Object.fromEntries and Object.entries

We can use the Object.fromEntries method to create an object from an array of arrays of key-value pairs.

And we can use Object.entries to return an array of arrays of key-value pairs of an object.

For example, we can write:

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

const newObj = Object.fromEntries(
  Object.entries(obj).map(
    ([key, value]) => ([key, value * 2])
  )
)
console.log(newObj)

We call Object.entries with obj to get the key-value pairs in an array.

Then we call map with a callback that destructures the key-value pairs.

And we return an array of key-value pairs.

We changed the value by multiplying it by 2.

Then we use Object.fromEntries to create an object from the new array of key-value pairs.

Therefore newObj is:

{a: 2, b: 4, c: 6}

as we have before.

Conclusion

We can map object properties to new values by using some handy object methods that are available in JavaScript’s standard library.

Categories
JavaScript Answers

How to Merge or Flatten an Array of JavaScript Arrays?

Sometimes, we want to merge or flatten an array of JavaScript arrays.

In this article, we’ll look at how to merge or flatten an array of JavaScript arrays.

Array.prototype.concat

The concat method lets us add the items from arrays passed in as arguments into the array it’s called on.

For instance, we can write:

const arrays = [
  ["1"],
  ["2"],
  ["3"],
  ["4"],
  ["5"],
  ["6"],
];
const merged = [].concat(...arrays);
console.log(merged);

We spread the entries in arrays to the concat method.

The all the entries from the arrays in arrays will be added to the empty array it’s called on and returned.

Therefore, we get [“1”, “2”, “3”, “4”, “5”, “6”] as the result of merged .

Array.prototype.flat

ES2019 comes with the flat method that lets us flatten an array with any level we want.

For instance, we can write:

const arrays = [
  ["1"],
  ["2"],
  ["3"],
  ["4"],
  ["5"],
  ["6"],
];
const merged = arrays.flat(1);
console.log(merged);

Then we get the same result as before.

We pass in 1 to flat to flatten the array one level.

If we don’t pass in an argument, then it’ll flatten recursively until there’re no more arrays left to flatten.

Write Our Own Function

Also, we can write our own function to flatten an array recursively.

For instance, we can write:

const arrays = [["1"], ["2"], ["3"], ["4"], ["5"], ["6"]];

const flatten = (arr) => {
  return arr.reduce((flat, toFlatten) => {
    if (Array.isArray(toFlatten)) {
      return flat.concat(...flatten(toFlatten));
    }
    return flat.concat(toFlatten);
  }, []);
};
const merged = flatten(arrays);
console.log(merged);

to create the flatten function.

We check if toFlatten is an array in the callback of reduce .

reduce lets us combine items from multiple arrays into one array.

If it is, then we return the return value flat.concat called with the flatten(toFlatten) spread into concat as arguments.

Otherwise, we just return the result of flat.concat(toFlatten) since toFlatten isn’t an array.

This means we can put it straight into the flat array.

The 2nd argument of reduce is the initial return value of reduce before anything is put into it.

Conclusion

The easiest way to flatten or merge nested arrays is to use the flat method that comes with arrays.

We can also use the concat method to flatten one level of a nested array.

Another choice is to create our own function to flatten an array.

Categories
JavaScript Answers

How to Add Days to JavaScript Date?

Adding days to a JavaScript date is an operation that sometimes we have to do.

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

The setDate Method

We can use the setDate method to add days to a date easily.

For instance, we can write:

const addDays = (date, days) => {
  const result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

const result = addDays(new Date(2021, 1, 1), 2)
console.log(result)

We have the addDays function to add days.

In the function, we pass in the date to the Date constructor.

Then we call setDate with the getDate method to get the day of the month.

And then we add the days to it.

And finally, we return the result , which has the new date with the days added to it.

Therefore, when we call it in the 2nd last line, we get:

'Wed Feb 03 2021 00:00:00 GMT-0800 (Pacific Standard Time)'

as the value of result .

setDate will compute the new date value no matter what number we pass into it.

For instance, if we write:

const addDays = (date, days) => {
  const result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

const result = addDays(new Date(2021, 1, 1), 100)
console.log(result)

Then result is 'Wed May 12 2021 00:00:00 GMT-0700 (Pacific Daylight Time)’ , which is still what we expect.

The setTime Method

Likewise, we can also call the setTime to set the timestamp of the date instead of days.

This lets us add a time more precisely.

For instance, we can write:

const date = new Date(2021, 1, 1)
const duration = 2;
date.setTime(date.getTime() + (duration * 24 * 60 * 60 * 1000));

date.getTime returns the timestamp in milliseconds.

Then we add the duration in days, converted to milliseconds by multiplying it by 24 * 60 * 60 * 1000 .

Then we get 'Wed Feb 03 2021 00:00:00 GMT-0800 (Pacific Standard Time)’ as the new value of date .

Conclusion

We can use native JavaScript date methods to add days to a JavaScript date.

Categories
JavaScript Answers

How to Remove Empty Elements from an Array in JavaScript?

Removing empty elements from a JavaScript array is something that we may have to do sometimes.

In this article, we’ll look at how to remove empty elements from a JavaScript array.

Array.prototype.filter

We can use an array instance’s filter method to remove empty elements from an array.

To remove all the null or undefined elements from an array, we can write:

const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
const filtered = array.filter((el) => {
  return el !== null && typeof el !== 'undefined';
});
console.log(filtered);

The filter method treated array holes as undefined .

So we should see:

[0, 1, 2, "", 3, 3, 4, 4, 5, 6]

as the value of filtered .

If we want to remove all falsy values, we can just pass in the Boolean function to filter .

For instance, we can write:

const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
const filtered = array.filter(Boolean);
console.log(filtered);

Falsy values include null , undefined , 0, empty string, NaN and false .

So they’ll return false if we pass them into the Boolean function.

Therefore, filtered is:

[1, 2, 3, 3, 4, 4, 5, 6]

If we want to return an array with only the numbers left, we can write:

const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
const filtered = array.filter(Number);
console.log(filtered);

Then we get the same result.

Or we can write:

const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
const filtered = array.filter(n => n);
console.log(filtered);

And also get the same result since the callback’s return value will be cast to a boolean automatically.

Lodash

Lodash also has a filter method that does the same thing as the native filter method.

For instance, we can write:

const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
const filtered = _.filter(array, Boolean);
console.log(filtered);

to filter out all the falsy values.

Then filtered is [1, 2, 3, 3, 4, 4, 5, 6] .

It also has a compact method that’s specially made to remove falsy values from an array.

For instance, we can write:

const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
const filtered = _.compact(array);
console.log(filtered);

Then we get the same result.

Conclusion

There’re various ways to remove falsy elements from a JavaScript with native array methods or Lodash.

Categories
JavaScript Answers

How to Convert a Unix Timestamp to Time in JavaScript?

Sometimes, we’ve to convert a Unix timestamp into a more human-readable format.

In this article, we’ll take a look at how to convert a Unix timestamp to a more readable format with JavaScript.

Use the Date Constructor and its Instance Methods

We can pass the Unix timestamp in milliseconds to the Date constructor to create a Date instance.

Then we can use its instance methods to get different parts of the date and put it into a string.

For instance, we can write:

const unixTimestamp = 15493124560
const date = new Date(unixTimestamp * 1000);
const hours = date.getHours();
const minutes = "0" + date.getMinutes();
const seconds = "0" + date.getSeconds();
const formattedTime = `${hours}:${minutes.substr(-2)}:${seconds.substr(-2)}`;

console.log(formattedTime);

We have the unixTimestamp in seconds.

Then we multiply that by 1000 and pass it into the Date constructor.

Next, we call getHours to get the hours from the Date instance.

And we call getMinutes to get the minutes.

And then we call getSeconds to get the seconds.

Then we put it all together in the formattedTime string.

To get the 2 digit minutes and seconds, we call substr with -2 to get the last 2 digits of them.

This trims off any leading zeroes from the number strings.

Then should see ’5:42:40' as the result.

To get the year, month, and date, we can write:

const unixTimestamp = 1613330814
const date = new Date(unixTimestamp * 1000);
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const year = date.getFullYear();
const month = months[date.getMonth()];
const dt = date.getDate();
const hours = date.getHours();
const minutes = "0" + date.getMinutes();
const seconds = "0" + date.getSeconds();
const formattedTime = `${year}-${month}-${dt} ${hours}:${minutes.substr(-2)}:${seconds.substr(-2)}`;

console.log(formattedTime);

We have the Unix timestamp in seconds.

So we’ve to multiply it by 1000 before passing it into the Date constructor.

Then we have a months array with the months abbreviations.

getFullYear returns the 4 digit year of a Date instance.

getMonth returns the month number of the Date instance, with 0 being January, 1 being February, all the way to 11 for December.

The getDate method returns the day of the month.

The rest of the code is the same.

Then formattedDate is '2021-Feb-14 11:26:54' .

The toLocaleTimeString Method

Another way to format a date into a human-readable string is to use the toLocaleTimeString method.

It takes the locale string as its argument.

For instance, we can write:

const str = new Date(1613331041675).toLocaleTimeString("en-US")
console.log(str)

We pass in the Unix timestamp converted to milliseconds to the Date constructor.

Then we call toLocaleDateString with the 'en-US' locale.

And we should get ‘11:30:41 AM’ as a result.

The Intl.DateTimeFormat Constructor

Another way we can format dates is to use the Intl.DateTimeFormat constructor.

For instance, we can write:

const dtFormat = new Intl.DateTimeFormat('en-US', {
  timeStyle: 'medium',
  timeZone: 'PST'
});
const str = dtFormat.format(new Date(1613331041675));
console.log(str)

We pass in the locale as the first argument of the constructor.

And we pass in some options as the 2nd argument.

timeStyle has the formatting style of the time.

timeZone sets the timezone of the time that’s returned.

Then we call format to return a string with the time.

And we get ‘11:30:41 AM’ as a result.

Conclusion

We can format a Unix timestamp with JavaScript with our own code or we can use native methods and constructors to format our dates.