Categories
JavaScript Answers

How to Compute the Sum and Average of the Elements in a JavaScript Array?

Sometimes, we want to compute the sum or average of the elements in a JavaScript array.

In this article, we’ll look at how to compute the sum and average of the elements in a JavaScript array.

Use a Loop

We can use the for-of loop to loop through an array to add all the numbers together to compute the sum.

Then to compute the average, we can divide the sum by the array’s length.

For instance, we can write:

const arr = [1, 2, 3]
let sum = 0;
for (const a of arr) {
  sum += a;
}

const avg = sum / arr.length;
console.log(sum)
console.log(avg)

We define an arr array with some numbers in it.

Then we define the sum variable and initialize it to 0.

Next, we add the for-of loop to loop through the arr entries.

a has the arr entry that’s being looped through.

In the loop body, we add the a value to the sum .

Then we create the avg variable and assign the quotient of the sum and arr.length to it.

Therefore, sum is 6 and avg is 2.

Use the Array.prototype.reduce Method

We can also use the array reduce instance method to compute the sum.

Then we can compute the average the same way as the previous example.

For instance, we can write:

const arr = [1, 2, 3]
const sum = arr.reduce((partialSum, a) => partialSum + a, 0)
const avg = sum / arr.length;
console.log(sum)
console.log(avg)

The reduce method takes a callback that has the partialSum and a .

Where partialSum is the partial sum returned after adding the arr entries that are iterated through.

a is the entry of arr being iterated through.

The callback returns the new partial sum.

The 2nd argument is the initial value of the sum .

The rest of the code is the same and we get the same result as the previous example.

Lodash sum and mean Methods

Lodash has the sum method that returns the sum of an array entries.

The mean method returns the average of the array entries.

For instance, we can write:

const arr = [1, 2, 3]
const sum = _.sum(arr)
const avg = _.mean(arr)
console.log(sum)
console.log(avg)

Both methods take the array we want to do the computation with as the argument.

Then we get the same result as before.

Conclusion

We can use Lodash or plain JavaScript to compute the sum and average of array entries.

Categories
JavaScript Answers

How to Filter Keys of an Object with Lodash?

Sometimes, we may want to extract some properties from an object and put them into a new object with Lodash.

In this article, we’ll look at how to get an object with only some of the keys from the original object.

Use the pickBy Method

Lodash comes with the pickBy method that takes an object and a callback that lets us return the condition of the keys we want to keep.

For instance, we can write:

const thing = {
  "a": 123,
  "b": 456,
  "abc": 6789
};

const result = _.pickBy(thing, (value, key) => {
  return _.startsWith(key, "a");
});
console.log(result)

Then we return an object with the properties from thing that starts with 'a' .

The first argument of pickBy is the object that we want to extract properties from.

The 2nd argument is the callback that returns the condition of the properties of the keys that we want to extract.

Then result is:

{
  "a": 123,
  "abc": 6789
}

Use the omitBy Method

We can also use the Lodash omitBy method to do the same thing.

For instance, we can write:

const thing = {
  "a": 123,
  "b": 456,
  "abc": 6789
};

const result = _.omitBy(thing, (value, key) => {
  return !_.startsWith(key, "a");
});
console.log(result)

The arguments are the same as pickBy except that the callback returns the condition for the keys that we don’t want in the returned object.

Therefore, result is the same as before.

Conclusion

We can use the pickBy or omitBy Lodash methods to extract the keys from an object and return an object with the properties we want from the original object.

Categories
JavaScript Answers

How to Render HTML to an Image with JavaScript?

Sometimes, we may want to render an HTML document or node to an image with JavaScript.

In this article, we’ll look at how to render an HTML document or node to an image with JavaScript.

Use the dom-to-image Library

The dom-to-image library makes converting an HTML node to an image easily.

For instance, if we have the following HTML:

<table>
  <tr>
    <td>col1 Val1</td>
    <td>col2 Val2</td>
  </tr>
  <tr>
    <td>col1 Val3</td>
    <td>col2 Val4</td>
  </tr>
</table>

<div>
</div>

Then we can add the library with the following script tag:

<script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js" integrity="sha512-01CJ9/g7e8cUmY0DFTMcUw/ikS799FHiOA0eyHsUWfOetgbx/t6oV4otQ5zXKQyIrQGTHSmRVPIgrgLcZi/WMA==" crossorigin="anonymous"></script>

Or we can add the library with NPM:

npm install dom-to-image

or Bower:

bower install dom-to-image

Then we can use it by writing the following JavaScript:

const table = document.querySelector("table");
const div = document.querySelector("div");
domtoimage.toPng(table)
  .then((dataUrl) => {
    const img = new Image();
    img.src = dataUrl;
    div.appendChild(img);
  })
  .catch((error) => {
    console.error(error);
  });

We call domtoimage.toPng with the element that we want to render to an image.

Then we get the dataUrl , which is the base64 string version of the image of the rendered element.

In the then callback, we create a new img element with the Image constructor.

Then we set the src property of it to dataUrl .

And then we call div.appendChild with img to append img to the div.

We can simplify this by using the async and await syntax:

const table = document.querySelector("table");
const div = document.querySelector("div");

(async () => {
  try {
    const dataUrl = await domtoimage.toPng(table)
    const img = new Image();
    img.src = dataUrl;
    div.appendChild(img);
  } catch (error) {
    console.error(error);
  }
})()

dataUrl is the same one as the then method callback parameter.

error is the same one as the one in the catch method callback parameter.

Conclusion

The dom-to-image Library lets us render an HTML node to an image easily with JavaScript.

Categories
JavaScript Answers

How to Iterate Through Table Rows and Cells in JavaScript?

Sometimes, we may want to iterate through HTML table rows and columns with JavaScript code.

In this article, we’ll look at how to iterate through table rows and cells with JavaScript.

Looping Through Tables and Rows and Cells with Plain JavaScript

We can loop through table rows and cells with plain JavaScript.

For instance, if we have the following HTML:

<table>  
  <tr>  
    <td>col1 Val1</td>  
    <td>col2 Val2</td>  
  </tr>  
  <tr>  
    <td>col1 Val3</td>  
    <td>col2 Val4</td>  
  </tr>  
</table>

Then we can get a table’s rows by using the rows property.

And to get the cells of each row, we can use the cells property.

To do this, we write:

const table = document.querySelector("table");  
for (const row of table.rows) {  
  for (const cell of row.cells) {  
    console.log(cell)  
  }  
}

We get the table with document.querySelector .

Then we use the for-of loop to loop through the table.rows .

And then we use the row.cells property to get the cells of each row.

To get the cell text, we can use the innerText property:

const table = document.querySelector("table");  
for (const row of table.rows) {  
  for (const cell of row.cells) {  
    console.log(cell.innerText)  
  }  
}

Conclusion

We can loop through table rows and cells easily with native JavaScript properties.

Categories
JavaScript Answers

How to Duplicate JavaScript Object Properties in JavaScript Another Object?

Oftentimes, we may want to duplicate a JavaScript object’s properties into another object.

In this article, we’ll look at how to duplicate JavaScript object properties in another JavaScript object.

Using the Object.assign Method

One way to duplicate an object’s properties in another object is to use the Object.assign method.

For instance, we can write:

const firstObject = {
  a: 1,
  b: 2
}
const secondObject = {
  c: 3
}
Object.assign(secondObject, firstObject);
console.log(secondObject)

We have the firstObject and secondObject objects with some properties.

Then we call Object.assign to copy the properties of the firstObject object into the secondObject .

Therefore, from the console log, we see that secondObject is:

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

after we call Object.assign .

If we don’t want to modify secondObject , we can write:

const firstObject = {
  a: 1,
  b: 2
}
const secondObject = {
  c: 3
}
const thirdObject = Object.assign({}, firstObject, secondObject)
console.log(thirdObject)

Then thirdObject is:

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

and secondObject is unmodified.

Spread Operator

Another way to copy an object’s property into another object is to use the spread operator.

For instance, we can write:

const firstObject = {
  a: 1,
  b: 2
}
const secondObject = {
  c: 3
}
const thirdObject = {
  ...firstObject,
  ...secondObject
}
console.log(thirdObject)

We created a thirdObject object which is created from spreading the properties of firstObject and secondObject into it.

Therefore, thirdObject is:

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

Conclusion

We can use the Object.assign method or the spread operator to copy properties from one object onto another.