Search code examples
javascriptinclude

Why include() function returning false always?


This is my code, This isCurrent?InvoiceIdStored always returing false no matter what ever the values I put for id

const invoiceIds = [4,2];
const isCurrentInvoiceIdStored = invoiceIds.includes(id => id === 4);

What I want is to check the given number is in this array or not?


Solution

  • Array.prototype.includes() the value to search for as parameter but you are passing a call back function as parameter:

    const invoiceIds = [4,2];
    const isCurrentInvoiceIdStored = invoiceIds.includes(4);
    console.log(isCurrentInvoiceIdStored);

    OR: You probably wanted to use Array.prototype.some() which accepts a function to test for each element

    const invoiceIds = [4,2];
    const isCurrentInvoiceIdStored = invoiceIds.some(id => id == 4);
    console.log(isCurrentInvoiceIdStored);