Categories
JavaScript Answers

How to get a list of duplicate objects in an array of objects with JavaScript?

Sometimes, we want to get a list of duplicate objects in an array of objects with JavaScript.

In this article, we’ll look at how to get a list of duplicate objects in an array of objects with JavaScript.

How to get a list of duplicate objects in an array of objects with JavaScript?

To get a list of duplicate objects in an array of objects with JavaScript, we can use the JavaScript array’s reduce method.

For instance, we write:

const values = [{
  id: 10,
  name: 'someName1'
}, {
  id: 10,
  name: 'someName2'
}, {
  id: 11,
  name: 'someName3'
}, {
  id: 12,
  name: 'someName4'
}];

const lookup = values.reduce((a, e) => {
  if (a[e.id]) {
    return {
      ...a,
      [e.id]: a[e.id] + 1
    }
  }
  return {
    ...a,
    [e.id]: 1
  }
}, {});

const dups = values.filter(e => lookup[e.id] > 1)
console.log(dups);

We call values.reduce with a callback that returns an object with the counts of the object give in values given the value of e.id.

If a[e.id] is defined, then we increment it by 1.

Otherwise, we set [e.id] to 1.

Then we get the id‘s of the objects in values with value bigger than 1.

As a result, dups is:

[
  {
    "id": 10,
    "name": "someName1"
  },
  {
    "id": 10,
    "name": "someName2"
  }
]

Conclusion

To get a list of duplicate objects in an array of objects with JavaScript, we can use the JavaScript array’s reduce method.

Categories
React Answers

How to add password strength validation with React, Formik and Yup?

Sometimes, we want to add password strength validation with React, Formik and Yup.

In this article, we’ll look at how to add password strength validation with React, Formik and Yup.

How to add password strength validation with React, Formik and Yup?

To add password strength validation with React, Formik and Yup, we can use Yup’s matches method.

For instance, we write:

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

const schema = yup.object().shape({
  password: yup
    .string()
    .required("Please Enter your password")
    .matches(
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})/,
      "Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and One Special Case Character"
    )
});

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

We create the validation schema with yup.object().shape.

Then we calk yup.string().required to make the field with name password required.

And then we call matches with a regex to enforce the password strength.

Next, we add the Formik component with the validationSchema prop set to schema.

In the render prop function, we add the Field prop with the name prop set to 'password' to make it validate with the Yup password property.

If there’re errors, then we show errors.password property.

Conclusion

To add password strength validation with React, Formik and Yup, we can use Yup’s matches method.

Categories
JavaScript Answers

How to insert or remove HTML content between div tags with JavaScript?

Sometimes, we want to insert or remove HTML content between div tags with JavaScript.

In this article, we’ll look at how to insert or remove HTML content between div tags with JavaScript.

How to insert or remove HTML content between div tags with JavaScript?

To insert or remove HTML content between div tags with JavaScript, we can set the innerHTML property of the element.

For instance, we write:

<div>
  hello world
</div>

to add a div.

Then we write:

const div = document.querySelector('div')
div.innerHTML = '<span>Something</span>';

to select the div with querySelector.

Then we set div.innerHTML to a string with a span to replace ‘hello world’ with the span.

Therefore, we should see ‘Something’ instead of ‘hello world’ displayed.

Conclusion

To insert or remove HTML content between div tags with JavaScript, we can set the innerHTML property of the element.

Categories
JavaScript Answers

How to add toast notifications with toastr and JavaScript?

Sometimes, we want to add toast notifications with toastr and JavaScript.

In this article, we’ll look at how to add toast notifications with toastr and JavaScript.

How to add toast notifications with toastr and JavaScript?

To add toast notifications with toastr and JavaScript, we can add the toastr script and CSS.

Then we can use the toastr object to create toasts.

For instance, we write:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.min.css" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.min.js"></script>

to add the toastr CSS and JavaScript file and jQuery.

jQuery is required for toastr.

Then we call toastr.success with a message string to show a success message by writing:

toastr.success('Success messages');

Conclusion

To add toast notifications with toastr and JavaScript, we can add the toastr script and CSS.

Then we can use the toastr object to create toasts.

Categories
JavaScript Answers

How to validate a ISO 8601 date using moment.js?

Sometimes, we want to validate a ISO 8601 date using moment.js.

In this article, we’ll look at how to validate a ISO 8601 date using moment.js.

How to validate a ISO 8601 date using moment.js?

To validate a ISO 8601 date using moment.js, we can use the isValid method.

For instance, we write:

const isValid = moment("2022-10-10T14:48:00", moment.ISO_8601).isValid()
console.log(isValid)

We call moment with the date string to parse and moment.ISO_8601 to parse the date string as an ISO 8601 date string.

Then we call isValid to return whether the date string is a valid date string according to the format we specified when parsing.

Therefore, isValid should be true since we the date string is a valid ISO 8601 date string.

Conclusion

To validate a ISO 8601 date using moment.js, we can use the isValid method.