Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if a value exists in array with .includes?

I know we can use .includes but I’ve been struggling to get it to work with my array. What I want is for my function to check if the value already exists and if it does to remove it from the array.

The value is a string. That value comes from an object that has .name as a property within the object.

0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}

1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go'}

I mapped through the data and assigned each button with a value of {d.name}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am using a button to get the value with this function below

and adding the values to ‘favs’.

const favs = [];

  function checkId(e) {
    if (e.target.value !== "")

      favs.push(e.target.value);

      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
    }

console.log
favs

[
    "3-Bit-CNC-Starter-Pack",
    "3-Bit-CNC-Starter-Pack"
]

How can I check to see if the value already exists within the array using .includes?

>Solution :

Just check before push:

function checkId(e) {
    if (e.target.value !== "") {
        if (!favs.includes(e.target.value)) {
            favs.push(e.target.value); 
            // other code here
        }   
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading