简体   繁体   中英

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}

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?

Just check before push:

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

["Sam", "Great", "Sample", "High"].includes("Sam"); // true

if not false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM