Home > Blockchain >  How to compare an array with a number ReactJS
How to compare an array with a number ReactJS

Time:07-04

I would like to compare canIBook() with id (increments) in the if statement, but it wont work.

I suspect I can't compare a number with an array, how would i go about fixing this?

The method canIBook() currently returns:

result: [11]

     const canIBook = () => {
    const no = freeSlotsList.filter((slot) => slot.booked === 1);
    const result = no.map((a) => a.id);
    return { result };
  };

The method with the if-statement:

const renderTableData = () => {
let id = 1;
const activeButton = () => {};
console.log(canIBook());
return (
  <tr>
    {days.map((val) => (
      <td>
        {timeSlot.map((n, i) => {
          if (id === canIBook()) {   //How do i make this true?
            return <h1>Works</h1>;
          } else {
            return (
              <button id={id  } className={activeButton}>
                {n} {id}
              </button>
            );
          }
        })}
      </td>
    ))}
  </tr>
);
};

CodePudding user response:

In that canIBook function you are actually returning an object, not an array. If you want to compare the id with the ids inside the array result you can do:

if (canIBook().result.includes(id)) {

Otherwise if you want to just return the array it would become:

const canIBook = () => {
 const no = freeSlotsList.filter((slot) => slot.booked === 1);
 const result = no.map((a) => a.id);
 return result;
};

And then:

if (canIBook().includes(id)) {
 //logic
}

CodePudding user response:

Following your code the function canIBook will return something like: { results: [1,2,3,4] }. Then to check if the id is inside the list returned by the canIBook you should do something like:

if (canIBook().results.includes(id)) {...}

CodePudding user response:

though, I don't understand the question clearly.

if you want to check if the id is in the Array you can use Array Methods such as include, filter or some.

if(freeSlotsList.some(slot => slot.booked == id)){
return <h1> It'works</h1>
} else {

....
}
  • Related