mig_08
mig_08

Reputation: 181

Filter out records from an array

I am trying to filter out records from one array if they exists in another array. Products is my initial array that contains all my products and productsToDelete contains 2 products as an example. What I am trying to achieve is, if productsToDelete has a product that already exists in Products it must filter it out.

Code:

const [products, setProducts] = useState<Product[]>([]);
const [productsToDelete, setProductsToDelete] = useState<Product[]>([]);


setProducts((products) =>
      products.filter((product) => product.id !== productsToDelete.map(val => { val.id}))
    );

Properties of Product array:

id?: string;
category: string;
subCategory: string;
brand: string;

Upvotes: 1

Views: 81

Answers (3)

Ross Sheppard
Ross Sheppard

Reputation: 870

Here's a code snippet filtering out the products that have the corresponding IDs to delete. I added some sample products to test it all out.

const products = [
  {
    id: 1,
    brand: 'Brand 1',
  },
  {
    id: 2,
    brand: 'Brand 2',
  },
  {
    id: 3,
    brand: 'Brand 3',
  },
];

const productsToDelete = [
  {
    id: 1,
    brand: 'Brand 1',
  },
];

const productIdsToDelete = new Set(productsToDelete.map(({ id }) => id));
const checkProductForId = (product) => !productIdsToDelete.has(product.id)
const updatedProducts = (products) => products.filter(checkProductForId);

// You can call `setProducts(updatedProducts);` from this point in the stack forward.

console.log(updatedProducts(products));

Upvotes: 1

Sarun UK
Sarun UK

Reputation: 6736

const idArrayToDelete = productsToDelete.map(({ id }) => id);
setProducts((products) =>
  products.filter(({id}) => !idArrayToDelete.includes(id))
);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370689

Make an array or Set of the IDs to remove first:

const idsToDelete = new Set(productsToDelete.map(({ id }) => id));
setProducts((products) =>
  products.filter((product) => !idsToDelete.has(product.id))
);

Upvotes: 1

Related Questions