Categories
JavaScript Answers

How to Count Certain Elements in a JavaScript Array?

Sometimes, we may want to count certain elements in a JavaScript array.

In this article, we’ll look at how to count certain elements in a JavaScript array.

Using the Array.prototype.filter Method

The Array.prototype.filter method lets us return an array with the items that meets the condition we’re looking for.

Therefore, we can use the length property of the array returned by filter to count the elements that meet the given condition.

For instance, we can write:

const arr = [1, 2, 3, 5, 2, 8, 9, 2]
const numEvens = arr.filter(x => x % 2 === 0).length
console.log(numEvens)

We have the arr with some numbers.

To count all the even numbers in the array, we can use the filter method with the callback that returns x % 2 === 0 to return an array that meets this condition, which are even numbers.

Then we can use the length property to get the number of entries in the array.

So we have numEvens equal 4 as seen from the console log.

Using the Array.prototype.reduce Method

Also, we can use the Array.prototype.reduce method to count the number of items that meet the given condition.

To count the number of even numbers with reduce , we write:

const arr = [1, 2, 3, 5, 2, 8, 9, 2]
const numEvens = arr.reduce((total, x) => (x % 2 === 0 ? total + 1 : total), 0)
console.log(numEvens)

We call reduce with a callback that takes the total and x parameters.

total is the total returned so far, and x is the value being iterated through to compute the total .

We return total + 1 if x % 2 is 0 and total otherwise.

0 in the 2nd argument is the initial value of total .

Therefore, we should get the same value for numEvens as before.

Conclusion

We can count certain elements in an array with the array instances filter or reduce methods.

Categories
JavaScript Answers

How to Set Time Delay in JavaScript?

Sometimes, we want to run some JavaScript code after a delay.

In this article, we’ll look at how to set a time delay in JavaScript.

Use the setTimeout Method

We can use the setTimeout method to run code after a time delay.

For instance, we can write:

setTimeout(() => {
  console.log('hello world')
}, 1000);

We pass in a callback to run after the delay as the first argument.

And we pass in the delay to wait until the callback is run in milliseconds as the 2nd argument.

Now we should see 'hello world' logged after 1 second.

Use the setTimeout Function in a Promise

We can use the setTimeout function in a promise so that we can easily use setTimeout multiple times sequentially.

To do this, we write:

const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
}
`
(async () => {
  console.log("Hello");
  await sleep(2000)
  console.log("world");
})()

We create the sleep function which returns promise created with the Promise constructor.

We pass in a callback that takes the resolve function and calls setTimeout with the resolve function so that the promise is resolved.

ms is the delay to wait in milliseconds until resolve is run.

Then we can use it in the async function below that.

So we should see 'Hello' logged first.

Then after 2 seconds, 'world' is logged.

Conclusion

We can run code with a time delay with the setTimeout method.

To use it sequentially, we can wrap it in a promise.

Categories
JavaScript Answers

How to Convert a Date String to Timestamp in JavaScript?

Sometimes, we may want to convert a date to UNIX timestamp in JavaScript.

In this article, we’ll look at ways to convert a date to a timestamp in JavaScript.

Use the Date.parse Method

We can use the Date.parse method to convert the date string into a timestamp.

For instance, we can write:

const toTimestamp = (strDate) => {  
  const dt = Date.parse(strDate);  
  return dt / 1000;  
}  
console.log(toTimestamp('02/13/2020 23:31:30'));

We create the toTimestamp method that calls the Date.parse method with a date string to parse it into a timestamp.

The unit is in milliseconds, so we’ve to divide it by 1000 to convert it to seconds.

Use the getTime Method

We can use the getTime method of a Date instance to convert the date string into a timestamp.

To use it, we write:

const toTimestamp = (strDate) => {  
  const dt = new Date(strDate).getTime();  
  return dt / 1000;  
}  
console.log(toTimestamp('02/13/2020 23:31:30'));

We create the Date instance with the Date constructor.

Then we call getTime to return the timestamp in milliseconds.

So we’ve to divide that by 1000 to get the number of seconds.

Moment.js’s unix Method

We can use the moment.js’s unix method to return a timestamp.

For instance, we can write:

const toTimestamp = (strDate) => {  
  const dt = moment(strDate).unix();  
  return dt;  
}  
console.log(toTimestamp('02/13/2020 23:31:30'));

We pass strDate into the moment function to return a moment object with the time.

Then we can call the unix method on that to return the timestamp.

The unix method returns the timestamp in seconds so we don’t have to divide the returned result by 1000.

Conclusion

We can use plain JavaScript or momnent.js to convert a date string into a UNIX timestamp.

Categories
JavaScript Answers

How to Get the First Entry of a JavaScript Object?

Sometimes, we may want to get the first entry of a JavaScript object.

In this article, we’ll look at how to get the first entry of a JavaScript object.

Object.keys

We can use the Object.keys method to return an array of object keys.

Therefore, we can use it to get the key name of the first object property.

For instance, we can write:

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

We have Object.keys(obj)[0] which returns 'a' since it’s the first entry in obj .

Object.values

We can use the Object.values method to return an array of object property values.

Therefore, we can use it to get the value of the first object property.

For instance, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
};
console.log(Object.values(obj)[0])

We have Object.values(obj)[0] which returns 1 since it’s the value of the first entry in obj .

Object.entries

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

Therefore, we can use it to get the key-value pair of the first object property.

For instance, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
};
console.log(Object.entries(obj)[0])

We have Object.entries(obj)[0] which returns [“a”, 1] since it’s the first key-value pair in obj .

Lodash toPairs Method

The Lodash toPairs method does the same thing as the Object.entries .

So we can use it if Object.entries isn’t available.

For instance, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
};
console.log(_.toPairs(obj)[0])

And we get [“a”, 1] as the result in the console log.

Conclusion

We can get the first entry of a JavaScript object with plain JavaScript or Lodash.

Categories
JavaScript Answers

How to Add or Remove Several Classes in One Single Instruction with classList?

Sometimes, we want to add or remove several classes in one single instruction with the classList API.

In this article, we’ll look at how to add or remove several classes in one instruction with classList .

Add or Remove Several Classes in One Single Instruction with classList

The add method takes one or more class name strings.

Therefore, we can use it to add more than one class at a time.

For instance, if we have the following HTML:

<div>

</div>

Then we can add more than one class by writing:

const div = document.querySelector('div')
div.classList.add("first", "second", "third");

If we have an array, then we can spread the entries as arguments:

const div = document.querySelector('div')
const list = ['first', 'second', 'third'];
div.classList.add(...list);

And we can replace the spread operator with apply :

const div = document.querySelector('div')
const list = ['first', 'second', 'third'];
div.classList.add.apply(
  div.classList,
  list
);

Set the className Property

We can also set the className property to a string with multiple classes with each separated by a space.

For instance, we can write:

const div = document.querySelector('div')
const list = ['first', 'second', 'third'];
div.className += list.join(' ');

to do the same thing.

The existing classes will be overwritten.

Conclusion

We can use the classList.add method or set the className property to add multiple class names to an element.