Max Andersson
Max Andersson

Reputation: 135

How to compare an array with a number ReactJS

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>
);
};

Upvotes: 0

Views: 44

Answers (3)

Mukhtar Mahamed
Mukhtar Mahamed

Reputation: 331

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 {

....
}

Upvotes: -1

Toni Bardina Comas
Toni Bardina Comas

Reputation: 1808

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)) {...}

Upvotes: 1

Hakim Abdelcadir
Hakim Abdelcadir

Reputation: 1326

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
}

Upvotes: 2

Related Questions