Categories
JavaScript Answers

How to calculate average with the array reduce method in JavaScript?

Sometimes, we want to calculate average with the array reduce method in JavaScript.

In this article, we’ll look at how to calculate average with the array reduce method in JavaScript.

How to calculate average with the array reduce method in JavaScript?

To calculate average with the array reduce method in JavaScript, we can call reduce with a callback to return the partial sum of the average.

For instance, we write:

const array = [129, 139, 155, 176]
const average = array.reduce((avg, value, _, {
  length
}) => {
  return avg + (value / length);
}, 0);
console.log(average)

to call array.reduce with a callback that return avg + (value / length), which is the partial sum of the average so far.

The 2nd argument of 0 so the initial value of avg is 0.

Therefore, average is 149.75.

Conclusion

To calculate average with the array reduce method in JavaScript, we can call reduce with a callback to return the partial sum of the average.

Categories
JavaScript Answers

How to scroll element to top of page by clicking anchor inside element or anywhere inside containing div ID with JavaScript?

Sometimes, we want to scroll element to top of page by clicking anchor inside element or anywhere inside containing div ID with JavaScript.

In this article, we’ll look ay how to scroll element to top of page by clicking anchor inside element or anywhere inside containing div ID with JavaScript.

How to scroll element to top of page by clicking anchor inside element or anywhere inside containing div ID with JavaScript?

To scroll element to top of page by clicking anchor inside element or anywhere inside containing div ID with JavaScript, we can call the scrollTo method.

For instance, we write:

<button>
  scroll
</button>

to add a button.

Then we write:

const button = document.querySelector('button')
button.onclick = () => {
  window.scrollTo(0, 0)
}

to select the button with querySelector.

Then we set button.onclick to a function that calls window.scrollTo with 2 0’s to scroll to the top of the page.

Conclusion

To scroll element to top of page by clicking anchor inside element or anywhere inside containing div ID with JavaScript, we can call the scrollTo method.

Categories
JavaScript Answers

How to remove duplicate objects from an array using JavaScript?

Sometimes, we want to remove duplicate objects from an array using JavaScript.

In this article, we’ll look at how to remove duplicate objects from an array using JavaScript.

How to remove duplicate objects from an array using JavaScript?

To remove duplicate objects from an array using JavaScript, we can use some array methods.

For instance, we write:

const a = [{
    "id": 10620,
    "name": "Things to Print"
  },
  {
    "id": 10620,
    "name": "Things to Print"
  },
  {
    "id": 4334,
    "name": "Interesting"
  }
]

const newA = [...new Set(a.map(JSON.stringify))].map(JSON.parse)
console.log(newA)

to remove duplicate objects from a by mapping a‘s entries to strings by calling map with JSON.stringify.

Then we create a new set from the returned array with Set.

Next, we spread that back to an array.

And then we call map on the new array with JSON.parse to convert it back to an object.

Therefore, newA is

[{
  id: 10620,
  name: "Things to Print"
}, {
  id: 4334,
  name: "Interesting"
}]

Conclusion

To remove duplicate objects from an array using JavaScript, we can use some array methods.

Categories
JavaScript Answers

How to pass all the values from an array into a function as arguments with JavaScript?

Sometimes, we want to pass all the values from an array into a function as arguments with JavaScript.

In this article, we’ll look at how to pass all the values from an array into a function as arguments with JavaScript.

How to pass all the values from an array into a function as arguments with JavaScript?

To pass all the values from an array into a function as arguments with JavaScript, we can use the spread and rest operators.

For instance, we write:

const f = (...args) => {
  console.log(args)
}

const a = ['a', 'b', 'c', 'd']
f(...a)

to define the function f that uses the rest operator in the arguments to accept an unlimited number of arguments.

args is an array with all the arguments.

Then we call f with array a‘s entries spread as the arguments of f with the spread operator.

Therefore, args is ["a", "b", "c", "d"].

Conclusion

To pass all the values from an array into a function as arguments with JavaScript, we can use the spread and rest operators.

Categories
JavaScript Answers React React Answers

How to detect network connection in a JavaScript React app, and if offline, hide a component from user?

Sometimes, we want to detect network connection in a JavaScript React app, and if offline, hide a component from user.

In this article, we’ll look at how to detect network connection in a JavaScript React app, and if offline, hide a component from user.

How to detect network connection in a JavaScript React app, and if offline, hide a component from user?

To detect network connection in a JavaScript React app, and if offline, hide a component from user, we can listen to the online and offline events.

For instance, we write:

import React from "react";

export default function App() {
  const [online, setOnline] = React.useState(navigator.onLine);

  const onNetworkStatusChange = () => {
    setOnline(navigator.onLine);
  };

  React.useEffect(() => {
    window.addEventListener("online", onNetworkStatusChange);
    window.addEventListener("offline", onNetworkStatusChange);

    return () => {
      window.removeEventListener("online", onNetworkStatusChange);
      window.removeEventListener("offline", onNetworkStatusChange);
    };
  }, []);

  return <>{online ? <div>online</div> : <div>offline</div>}</>;
}

to call window.addEventListener with 'online' and 'offline' to listen for the online and offline events.

online event is emitted when the device is online and the offline event is emitted otherwise.

We set the event listener of each event to onNetworkStatusChange.

In it, we call setOnline with navigator.onLine to set the value of online.

navigator.onLine is true if the device is online and false otherwise.

We also call removeEventListener in the function we return in the useEffect callback to remove the listeners once the component is unmounted.

Then when the device is online we display ‘online’.

Otherwise, we display ‘offline’.

Conclusion

To detect network connection in a JavaScript React app, and if offline, hide a component from user, we can listen to the online and offline events.