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.

Categories
JavaScript Answers

How to Measure the Time Taken by a JavaScript Function to Execute?

Sometimes, we’ve to find out how long a JavaScript function takes to run.

In this article, we’ll look at how to measure the time taken by a JavaScript function to run.

The performance.now() Method

One way to measure the time taken by a JavaScript to code to run is to use the performance.now method.

It returns the timestamp of the current time in milliseconds.

Therefore, to use it, we can write:

const t0 = performance.now()  
for (let i = 0; i <= 1000; i++) {  
  console.log(i)  
}  
const t1 = performance.now()  
console.log(t1 - t0, 'milliseconds')

We call performance.now before and after running our code.

Then we subtract the time after the code is run from the time before it’s run to get the run time of the code.

The console.time and console.timeEnd Methods

We can use the console.time method to start measure the time it takes for a piece of code to run.

Then we can use the console.timeEnd method to stop the measurement.

They both take a string as the argument that we can use as an identifier of what we’re measuring.

So to start the measurement, we call console.time with a string identifier.

And to end the measurement, we call console.timeEnd with the same string identifier that we used with console.time .

For instance, we can write:

console.time('loop')  
for (let i = 0; i <= 1000; i++) {  
  console.log(i)  
}  
console.timeEnd('loop')

After calling timeEnd , we should get the identifier string with the time between the console.time and console.timeEnd method calls logged in milliseconds.

Conclusion

We can measure the time it takes to run a piece of JavaScript with the performance interface or console methods.

Categories
JavaScript Answers

How to Trim Whitespace from a String in JavaScript?

Trimming whitespace from a string is an operation that we have to do sometimes.

In this article, we’ll look at how to trim whitespace from a string in JavaScript.

String.prototype.trim

A simple way to trim whitespace from a string is to use the trim method available with JavaScript strings.

We just call it by writing:

console.log(' abc '.trim())

String.prototype.trimLeft

If we only need to trim whitespace from the start of the string, we can use the trimLeft method.

For instance, we can write:

console.log(' abc '.trimLeft())

to trim whitespace from the beginning of the string.

String.prototype.trimRight

If we only need to trim whitespace from the end of the string, we can use the trimRight method.

For instance, we can write:

console.log(' abc '.trimRight())

to trim whitespace from the end of the string.

Trim String with Regex Replace

We can search for whitespace with a regex and call replace to replace all the whitespace with empty strings.

For instance, we can write:

console.log(' abc '.replace(/^\s+|\s+$/g, ''))

to trim whitespace from both the start and the end.

^\s+ is the pattern for searching for whitespace at the start of the string.

^ means the start of the string.

Likewise, \s+$ is the pattern for searching for whitespace at the end of the string.

And $ means the end of the string.

The g flag means we search for all instances of whitespace in the string.

Then to trim only starting whitespace, we write:

console.log(' abc '.replace(/^\s+/, ''))

And to trim only trailing whitespace, we write:

console.log(' abc '.replace(`/\s+$/`, ''))

And to trim all kinds of whitespace, we write:

console.log(' abc '.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, '').replace(/\s+/g, ' '))

This includes the newline character in addition to spaces since we have \n in the regex.

Conclusion

We can trim whitespace from a string with built-in JavaScript methods or with regex replace.

Categories
JavaScript Answers

How to Trigger a Button Click with JavaScript on the Enter Key in a Text Box?

If we have a text box on our web page, we may want to trigger a button click when we press the enter key.

In this article, we’ll look at how to trigger a button click with JavaScript when an enter key is pressed in a text box.

Use the click Method

We can call the click method that’s available with HTML element node objects to click an element programmatically.

For instance, we can write the following HTML:

<input type="text" id="txtSearch"  />
<input type="button" id="btnSearch" value="Search" />

Then we can write the following JavaScript code to check for the Enter keypress and trigger a button click afterwards:

const txtSearchEl = document.getElementById('txtSearch')
const btnSearchEl = document.getElementById('btnSearch')

txtSearchEl.addEventListener('keydown', (event) => {
  if (event.keyCode == 13) {
    btnSearchEl.click()
  }
})

btnSearchEl.addEventListener('click', () => {
  console.log('search button clicked')
})

We get the 2 inputs with document.getElementById .

Then we call addEventListener on txtSearchEl with the 'keydown' string as the first argument to add an event listener for the keydown event.

Next, we pass in a callback as the 2nd argument that runs when the event is triggered.

In the callback, we check the keyCode property to see if it’s 13.

If it is, then the Enter key is pressed.

Then we get the btnSearchEl HTML element node object, which is the button below the text box, and call click on it.

The click method triggers the click programmatically.

Next, we add a click listener to the btnSearchEl element node object to do something when a button is clicked.

And so when click is called, we should see 'search button clicked' logged.

We can also check the event.key property instead of the event.keyCode property.

For instance, we can write:

const txtSearchEl = document.getElementById('txtSearch')
const btnSearchEl = document.getElementById('btnSearch')

txtSearchEl.addEventListener('keydown', (event) => {
  if (event.key === "Enter") {
    btnSearchEl.click()
  }
})

btnSearchEl.addEventListener('click', () => {
  console.log('search button clicked')
})

event.key returns a string with the name of the key we pressed, so it’s more intuitive than checking a key code.

Conclusion

We can trigger a button click after a key press by watching the keydown event with an event listener.

In the event listener, we call click on the button element object to trigger the click programmatically.

And we can attach a click event listener on the button element to do something when we click on the button.