Categories
JavaScript Answers

How to Call Javascript Array’s reduce Method on an Array of Objects?

Sometimes, we’ve to call the JavaScript array’s reduce method on an array of objects and we want to get a result from it.

In this article, we’ll look at how to JavaScript array’s reduce method to produce a result and put it in an object.

Calling reduce on an Array of Objects

To call reduce on an array of objects, we can get the object from the callback.

To do this, we write:

const arr = [{
  x: 1
}, {
  x: 2
}, {
  x: 3
}];
const result = arr.reduce((a, b) => ({
  x: a.x + b.x
}));
console.log(result)

We have the arr array.

And we call reduce on it with a callback by returning an object with the x property and the x property from a and b added together.

a and b are the objects that are from the arr array.

We can also get the value of the x property and just add them together.

For instance, we can write:

const arr = [{
  x: 1
}, {
  x: 2
}, {
  x: 3
}];
const result = arr.reduce((acc, obj) => {
  return acc + obj.x;
}, 0);
console.log(result)

acc is the sum of all the x property values together.

obj has the object in arr that we’re iterating through.

We return acc + obj.x to return the sum.

The 2nd argument is the initial value of the returned result.

We set it to 0 so that we can add the x values together.

And so result is 6.

Also, we can destructure the object in the 2nd parameter of the callback by writing:

const arr = [{
  x: 1
}, {
  x: 2
}, {
  x: 3
}];
const result = arr.reduce((acc, { x }) => {
  return acc + x;
}, 0);
console.log(result)

Using map and reduce Together

Also, we can use the map and reduce methods together.

We use map to return an array of numbers from the x property.

And then we can use reduce to add all the numbers together.

For instance, we can write:

const arr = [{
  x: 1
}, {
  x: 2
}, {
  x: 3
}];
const result = arr.map((a) => a.x)
  .reduce((a, b) => a + b);
console.log(result)

We call map with a callback to return the value of x .

And then we call reduce with a callback to return the sum.

Conclusion

We can call reduce on an array of objects by getting the object from the parameter and do what we want with it.

Or we can use map to extract the values we want from the array entries and call reduce to combine the values the way we want.

Categories
JavaScript Answers

How to Inspect the JavaScript FormData Instance?

If we have an HTML form, then the entered data may be stored in an object that’s created from the FormData instance.

In this article, we’ll look at how to inspect the object created from the FormData constructor.

The for-of Loop with the entries Method

We can use the for-of loop to loop through the key-value pairs of the FormData instance to inspect their values.

To get the key-value pairs, we can use the entries method of the FormData instance to return the key-value pairs in an array.

For example, we can write:

const formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

for (const [key, value] of formData.entries()) {
  console.log(key, value);
}

Then we get:

key1 value1
key2 value2

We create the formData object with the FormData constructor.

Then we call append with the key and value respectively to add the entry to the formData object.

Next, we call formData.entries to return an array with the key-value pairs in an array.

In the for-of loop, we destructure the key-value pairs and log them with console.log .

Omit the entries Method

We can omit the entries method since formData is an iterable object.

It has an iterator to return the key-value pairs.

Therefore, we can shorten it to:

const formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

for (const [key, value] of formData) {
  console.log(key, value);
}

Object.fromEntries

We can also use Object.fromEntries to get the key-value pairs into an object that we can inspect easily.

This works because it a FormData instance has an iterator that returns the key-value pair arrays in an array.

For instance, we can write:

const formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
console.log(Object.fromEntries(formData))

Then we get:

{key1: "value1", key2: "value2"}

from the console log.

Using the Response Constructor

We can use the Response constructor to convert the FormData instance to text we can inspect easily.

For instance, we can write:

const formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

(async () => {
  const text = await new Response(formData).text()
  console.log(text)
})()

The text method returns a promise, so we put it in an async function.

Then text is something like:

------WebKitFormBoundaryzCHPG30oZJEPIn1B
Content-Disposition: form-data; name="key1"

value1
------WebKitFormBoundaryzCHPG30oZJEPIn1B
Content-Disposition: form-data; name="key2"

value2
------WebKitFormBoundaryzCHPG30oZJEPIn1B--

If we only care about inspecting it, then we can use the text method.

Conclusion

There’re several ways to inspect a FormData instance.

It’s an iterable object, so we can use the for-of loop with it.

Also, we can convert it to a Response instance and use the text method to inspect it.

Categories
JavaScript Answers

How to do Case Insensitive JavaScript String Comparison?

Sometimes, we’ve to case-insensitive JavaScript string comparison in our code.

In this article, we’ll look at how to do a case-insensitive JavaScript string comparison.

Convert Both Strings to Upper Case

One way to do a case-insensitive string comparison with JavaScript is to compare them both after converting them to upper case.

For instance, we can write:

const string1 = 'abc'  
const string2 = 'Abc'  
const areEqual = string1.toUpperCase() === string2.toUpperCase();  
console.log(areEqual);

We have string1 and string2 that have the same letter but with different cases.

Then we convert them both to upper case with the toUpperCase method.

And then we log the value of areEqual .

The console log should log true since they’re both the same when converted to upper case.

Convert Both Strings to Lower Case

We can convert both strings to lower case and do our comparisons that way.

For instance, we can write:

const string1 = 'abc'  
const string2 = 'Abc'  
const areEqual = string1.toLowerCase() === string2.toLowerCase();  
console.log(areEqual);

Then areEqual should be true since they’re the same when they’re both converted to lower case.

The localeCompare Method

We can use the JavaScript string’s localeCompare method to do case-insensitive string comparisons.

If they’re the same, then it returns 0.

For instance, we can write:

const string1 = 'abc'  
const string2 = 'Abc'  
const areEqual = string1.localeCompare(string2, undefined, {  
  sensitivity: 'base'  
});  
console.log(areEqual);

We call localeCompare on string1 and pass string2 into the first argument to compare them.

Then in the 3rd argument, we pass in an object with the sensitivity set to 'base' to ignore the case when comparing.

Then areEqual should be 0 since they’re the same when the case is ignored.

Conclusion

To do a case-insensitive comparison with 2 JavaScript strings, we can convert both strings to upper case or lower case.

Also, we can use the string localeCompare method to compare both strings in a case-insensitive manner by setting the sensitivity setting.

Categories
JavaScript Answers

How to Create a Two-Dimensional Array in JavaScript?

Sometimes we’ve to create a 2-dimensional array in a JavaScript app.

In this article, we’ll look at how to create 2-dimensional arrays with JavaScript.

Nested Arrays

In JavaScript, 2-dimensional arrays are just nested arrays.

For instance, we can write:

const arr = [
  [1, 2],
  [3, 4],
  [5, 6]
];
console.log(arr[0][0]);
console.log(arr[0][1]);
console.log(arr[1][0]);
console.log(arr[1][1]);
console.log(arr);

We have arrays in an array.

Then we can access the nested items with square brackets.

The first console log logs 1.

The 2nd console log logs 2.

The 3rd console log logs 3.

And the last console log logs 4.

Create an Empty Two Dimensional Array

To create an empty 2-dimensional array, we can use the Array.from and Array constructors.

For instance, we can write:

const arr = Array.from(Array(2), () => new Array(4))
console.log(arr);

The Array.from method lets us create an array from another array.

The first argument is the array we want to derive from the new array from.

And the 2nd argument is a function that maps the values from the first array to the values we want.

We return an array with 4 items.

Therefore, we get a 2×4 2-dimensional array returned.

Also, we can create a 2-dimensional array with just the Array function.

For instance, we can write:

const arr = Array(2).fill().map(() => Array(4));
console.log(arr);

We call the fill method to fill the empty slots.

This way, we can call map to and return arrays in the map callback to create the 2-dimensional array.

Conclusion

We can create JavaScript 2–dimensional arrays by nesting array literals.

Also, we can create 2-dimensional arrays with the Array function.

Categories
JavaScript Answers

How to Convert a Floating-Point Number to a Whole Number in JavaScript?

Converting a floating-point number to a whole number is something that we’ve to do sometimes in JavaScript apps.

In this article, we’ll look at how to convert a JavaScript floating-point number to a whole number.

Math.floor

The Math.floor method lets us round a number down to the nearest integer.

For instance, we can use it by writing:

const intvalue = Math.floor(123.45);  
console.log(intvalue)

Then we get 123 as the value of intValue .

Math.ceil

The Math.ceil method lets us round a number up to the nearest integer.

For instance, we can write:

const intvalue = Math.ceil(123.45);  
console.log(intvalue)

Then intValue is 124.

Math.round

The Math.round method lets us round a number down to the nearest integer if the first decimal digit is 4 or lower.

Otherwise, it rounds the number up to the nearest integer.

For instance, if we have:

const intvalue = Math.round(123.45);  
console.log(intvalue)

Then intValue is 123.

Math.trunc

The Math.trunc method lets us return the integer part of a number by removing the fractional digits.

For example, we can write:

const intvalue = Math.trunc(123.45);  
console.log(intvalue)

Then intValue is 123.

parseInt

The parseInt function lets us convert a floating-point number to an integer.

It works like Math.trunc in that it removes the fractional digits from the returned number.

For example, we can write:

const intvalue = parseInt(123.45);  
console.log(intvalue)

And intValue is 123.

To make sure that we return a decimal number, we pass 10 into the 2nd argument:

const intvalue = parseInt(123.45, 10);  
console.log(intvalue)

Conclusion

JavaScript provides a few functions and methods to lets us convert floating-point numbers to integers.