Categories
JavaScript Answers

How to Get a JavaScript String’s Length in Bytes?

We can use the Blob constructor to get the size of a string in bytes.

For instance, we can write:

const {
  size
} = new Blob(["hello"]);
console.log(size)

We create a blob from a string with the Blob constructor.

Then we get the size property of the blob to get the size.

We should see that size is 5 from the console log.

Get a JavaScript String’s Length in Bytes with TextEncoder

We can also use the TextEncoder constructor to get the size of a string in bytes.

For example, we can write:

const size = (new TextEncoder().encode('hello')).length
console.log(size)

We create a new TextEncoder instance and call encode on it with the string we want to get the size from.

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

Categories
JavaScript Answers

How to Get a Number of Random Elements from a JavaScript Array?

To get a number of random elements from a JavaScript array, we can shuffle it then call slice to get the first n elements from the shuffled array.

For instance, we can write:

const n = 5;
const items = [10, 6, 19, 16, 14, 15, 2, 9, 5, 3, 4, 13, 8, 7, 1, 12, 18, 11, 20, 17];
const sample = items
  .sort(() => Math.random() - 0.5)
  .slice(0, n);
console.log(sample)

We call sort on items with a callback that returns a number between -0.5 and 0.5 to return an array with the items shuffled around.

Then we call slice with 0 and n to get the first n items in the shuffled array.

Then sample has the first 5 shuffled items from items since we set n to 5.

Categories
JavaScript Answers

How to Convert an Array of Objects into One Object in JavaScript?

We can use the JavaScript array reduce method to combine objects in an array into one object.

For instance, we can write:

const arr = [{
  key: "11",
  value: "1100"
}, {
  key: "22",
  value: "2200"
}];
const object = arr.reduce((obj, item) => ({
  ...obj,
  [item.key]: item.value
}), {});
console.log(object)

We have the arr array which we want to combine into one object.

To do that, we call reduce with a callback that returns an object with obj spread into the returned object.

And we add the item.key property with itemn.value as its value.

Therefore, object is:

{11: "1100", 22: "2200"}

Use the Array.prototype.map and Object.assign Methods

Another way to combine an array of objects into one object is to map each entry into their own object.

Then we can combine them all into one with Object.assign .

For instance, we can write:

const arr = [{
  key: "11",
  value: "1100"
}, {
  key: "22",
  value: "2200"
}];
const mapped = arr.map(item => ({
  [item.key]: item.value
}));
const object = Object.assign({}, ...mapped);
console.log(object)

We call map with a callback that returns an object the key and value of the object.

Then we spread mapped into Object.assign as arguments to add the properties in the mapped objects into the empty object.

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

Categories
JavaScript Answers

How to Compare Only Dates in Moment.js?

We can use the isAfter method to check if one date is after another.

For instance, we can write:

const isAfter = moment('2010-10-20').isAfter('2010-01-01', 'year');  
console.log(isAfter)

We create a moment object with a date string.

Then we call isAfter on it with another date string and the unit to compare.

Therefore isAfter is false since we compare the year only.

There’s also the isSameOrAfter method that takes the same arguments and lets us compare if one date is the same or after a given unit.

So if we have:

const isSameOrAfter = moment('2010-10-20').isSameOrAfter('2010-01-01', 'year');  
console.log(isSameOrAfter)

Then isSameOrAfter is true since both dates have year 2010.

The isBefore method lets us compare is one date is before another given the unit to compare with.

So if we have:

const isBefore = moment('2010-10-20').isBefore('2010-01-01', 'year');  
console.log(isBefore)

Then isBefore is false since they have the same year.

isSame compares if 2 dates have the same unit.

For instance, if we have:

const isSame = moment('2010-10-20').isSame('2010-01-01', 'year');  
console.log(isSame)

Then isSame is true since they both have year 2010.

Categories
JavaScript Answers

How to Swap the Keys and Values of a JavaScript Object?

We can use the Object.entries to get an object’s keys and values in an array of key-value pairs.

And we can use Object.fromEntries to convert an array of key-value pairs to an object.

Therefore, we can use them to swap the keys and values of an object.

For instance, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
}
const swapped = Object.fromEntries(Object.entries(obj).map(a => a.reverse()))
console.log(swapped)

We have the obj opbject that we want to swap the keys and values for.

To do that, we call Object.entries with obj .

Then we call map to call reverse on each entry to do the swap.

And then we call Object.fromEntries on the array returned by map to convert it back to an object.

And we get:

{1: "a", 2: "b", 3: "c"}

as the value of swapped .

We can do the same swap by using destructuring:

const obj = {
  a: 1,
  b: 2,
  c: 3
}
const swapped = Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]))
console.log(swapped)

We destructure the parameter of the map callback and return the 2 items swapped.