Remove object from array in some conditions

Viewed 45

I need to update the filters in order of some situations.

while in some data conditions I need to remove 1 item from an array.

Here is the code

    useEffect(() => {
        let canceled = false;
        const filters = [
            new CheckFilterBuilder('badges', 'Badges'),
            new CategoryFilterBuilder('category', 'Categories'),
            new RangeFilterBuilder('price', 'Price'),
            new CheckFilterBuilder('brand', 'Brand'),
        ];
        console.log(filters);

        dispatch({ type: 'FETCH_PRODUCTS_LIST' });
        shopApi.getProductsList(
            state.options,
            { ...state.filters, category: categorySlug }, filters,
        ).then((productsList) => {
            if (canceled) {
                return;
            }

            dispatch({ type: 'FETCH_PRODUCTS_LIST_SUCCESS', productsList });
        });

        return () => {
            canceled = true;
        };
    }, [dispatch, categorySlug, state.options, state.filters]);

I tried a solution with if() statement but I couldn't put it in the remove item I want is

new RangeFilterBuilder('price', 'Price'),

since it does not accept if() or anything else I couldn't do it.

2 Answers

You could do that by creating a filter that's empty (or has known filters already included) and add (push) additional ones based on the condition

const filters = [new CheckFilterBuilder('badges', 'Badges')];

if (condition === true) {filters.push(new CategoryFilterBuilder('category', 'Categories'))}
if (condition === true) {filters.push(new RangeFilterBuilder('price', 'Price'))}
if (condition === true) {filters.push(new CheckFilterBuilder('brand', 'Brand'))}

you could slice it out of there?

const slicer = (arr, index) => {
  if (index === 0) { arr = [...arr.slice(1)]; }
  else { arr = [...arr.slice(0, index),...arr.slice(index + 1)]; }
  return arr; //or not. I think arrays pass by reference anyway
}

Related