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.

Categories
JavaScript Answers

How to convert the Date.now value to a readable format with JavaScript?

Sometimes, we want to convert the Date.now value to a readable format with JavaScript.

In this article, we’ll look at how to convert the Date.now value to a readable format with JavaScript.

How to convert the Date.now value to a readable format with JavaScript?

To convert the Date.now value to a readable format with JavaScript, we can use the toLocaleString method.

For instance, we write:

const date = new Date(Date.now());
console.log(date.toLocaleDateString());

to call Date.now to return a timestamp.

Then we create a Date instance from the timestamp and assign it to date.

Finally, we call date.toLocaleString to return a localized date string.

Conclusion

To convert the Date.now value to a readable format with JavaScript, we can use the toLocaleString method.

Categories
JavaScript Answers React React Answers

How to validate is either string or array of strings with Yup, React and JavaScript?

Sometimes, we want to validate is either string or array of strings with Yup, React and JavaScript.

In this article, we’ll look at how to validate is either string or array of strings with Yup, React and JavaScript.

How to validate is either string or array of strings with Yup, React and JavaScript?

To validate is either string or array of strings with Yup, React and JavaScript, we can use the mixed and when methods.

For instance, we write:

import React from "react";
import * as yup from "yup";
import { Formik, Form, Field } from "formik";

const validationSchema = yup.object().shape({
  email: yup
    .mixed()
    .when("isArray", {
      is: Array.isArray,
      then: yup.array().of(yup.string()),
      otherwise: yup.string()
    })
    .required()
});

export default function App() {
  return (
    <Formik
      initialValues={{ email: "" }}
      validationSchema={validationSchema}
      onSubmit={(values) => {
        console.log(values);
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <Field name="email" />
          {errors.email && touched.email ? <div>{errors.email}</div> : null}
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  );
}

to add a form with the Formik and Form components.

We set the validationSchema prop to an object returned by object and shape to let us validate the value object.

We set the email property of the schema object to an object returned by mixed and when to add conditional validation.

And we set is to Array.isArray to check if email is an array.

If it’s true, then we validate that is an array of strings by setting then to yup.array().of(yup.string()).

Otherwise, we set the otherwise property to yup.string to validate that email is a string.

Conclusion

To validate is either string or array of strings with Yup, React and JavaScript, we can use the mixed and when methods.