Categories
JavaScript Answers

How to call array.push() if item does not exist with JavaScript?

Spread the love

To call array.push() if item does not exist with JavaScript, we use findIndex to check for item before we call push.

For instance, we write

const arrayObj = [
  { name: "bull", text: "red" },
  { name: "tom", text: "tasty" },
  { name: "tom", text: "tasty" },
];
const index = arrayObj.findIndex((x) => x.name == "bob");
if (index === -1) {
  arrayObj.push(obj);
} else {
  console.log("object already exists");
}

to call findIndex to get the index of the first object with name equal to 'Bob'.

If it returns -1, then we call push to append obj as the last item of the arrayObj array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.