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.

someone
  • 681
  • 4
  • 18
  • 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. – Mirza Umair Oct 24 '22 at 11:59

1 Answers1

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);
kind user
  • 40,029
  • 7
  • 67
  • 77