0

I have the following code.

    const data = [
    { id: 1, serviceId: 1, title: "A" },
    { id: 2, serviceId: 3, title: "T" },
    { id: 3, serviceId: 45, title: "R" },
    { id: 4, serviceId: 55, title: "Q" },
    { id: 5, serviceId: 58, title: "S" },
    { id: 6, serviceId: 63, title: "zx" },
    { id: 7, serviceId: 66, title: "y" }
    ];

    const secondData = [55, 66, 1, 58];

    const myArrayFiltered = data.filter((el) => {
    return secondData.some((f) => {
      return f === el.serviceId;
    });
    });

     return (
       <div className="App">
        {myArrayFiltered.map((el) => (
          <div key={el?.id}>
           {el.title}-{el.serviceId}
          </div>
        ))}
      </div>
     );

I have data that should be filtered with secondData array.

The final result should be:

    { id: 2, serviceId: 3, title: "T" },
    { id: 3, serviceId: 45, title: "R" },
    { id: 6, serviceId: 63, title: "zx" },

for filtering, I wrote the following code.

      const myArrayFiltered = data.filter((el) => {
        return secondData.some((f) => {
          return f === el.serviceId;
     });

But it's returning the following:

   {id: 1, serviceId: 1, title: "A" },
   { id: 4, serviceId: 55, title: "Q" },
   { id: 5, serviceId: 58, title: "S" },
   { id: 7, serviceId: 66, title: "y" }

how can I fix that ?

Thanks.

1
  • according to your logic, you are getting the correct data, because you are comparing your data with [55, 66, 1, 58]. try to compare it with [3, 45, 63]. Or try to use !== operator to get the desired result. Commented Oct 24, 2022 at 11:59

1 Answer 1

0

You don't actually need Array#some. You could simply use Array#includes instead, to check whether current serviceId is or is not in the secondData array.

const data = [
    { id: 1, serviceId: 1, title: "A" },
    { id: 2, serviceId: 3, title: "T" },
    { id: 3, serviceId: 45, title: "R" },
    { id: 4, serviceId: 55, title: "Q" },
    { id: 5, serviceId: 58, title: "S" },
    { id: 6, serviceId: 63, title: "zx" },
    { id: 7, serviceId: 66, title: "y" }
];


const secondData = [55, 66, 1, 58];

const myArrayFiltered = data.filter((el) => !secondData.includes(el.serviceId));

console.log(myArrayFiltered);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.