Home > Software engineering >  How to check what does an array contains in React JS?
How to check what does an array contains in React JS?

Time:10-03

I have a variable that collects an array of strings and I want to validate like: if the array contains an string with the word "x" then add "y" example:

enter image description here

So I tried do something like: if my "grade/course" is "Prekinder" then add "PE-" RNG (last one is manually set up) but I got 2 failures this was my attempt:

const register = (e) => {
        e.preventDefault();
        
        let id = Math.floor(Math.random() * (99999   1));
        console.log(grado)
        const docId = "fail2";
        if (grado.contains == "Prekínder-3" || grado.contains == "Prekínder" || grado.contains == "Kínder"){
            docId = `PE-` id;
        }

.......... Some smart code that is not relevant for this
}

Any help/tip/documentation is welcome.

Update This is how I do the input is from a Multi select

<Select className= "SelectMultiple"
                placeholder = "Seleccionar..."
                options={multipleGrado}
                isMulti 
                required
                onChange={setGrados}

and this is how it looks in the firebase

enter image description here

CodePudding user response:

let a = {
  cantidad: 10,
  id: "135",
  grado: ["prekinder-3", "prekinder", "kinder"],
};

function check(a) {
  if (
    a.grado.find((element) => {
      if (element.includes("inder")) {
        return true;
      }
    })
      ? true
      : false
  ) {
    a.id = "PE-"   a.id;
  }
  console.log(a);
}

check(a);

hope it will help you. Find will check only one matched element and returns the element. filter will check every element but in your case find will be good I guess. Try yourself and see if you can achieve what you are trying.

  • Related