2

I need a bit of help to remove items from an array. I have a number of check boxes, each have a dynamically created data attribute. On un-checking a check box I want to remove items from an array which match item.sector value of each array item. I can't quite get it working. Any help would be appreciated.

let mapMarkers = [];

function addFilter(self) {
        const markerObject = filterObject[self.id];
        const markerID = markerObject[0]["id"];
        const dataSetSector = self.dataset.sector;
        const dataSetYear = self.dataset.year;

        if (self.checked) {
            mapMarkers.push(markerObject);
        } else {
            // data attribute SECTOR exists
            if (self.hasAttribute("data-sector")) {
                mapMarkers = mapMarkers.reduce((acc, curr) => {             
                    if (curr.sector !== dataSetSector) acc.push(curr);
                    return acc;
                });
            } 
            // data attribute YEAR exists
            else if (self.hasAttribute("data-year")) {
                mapMarkers = mapMarkers.reduce((acc, curr) => {         
                    if (curr.sector !== dataSetYear) acc.push(curr);
                    return acc;
                });
            }
        }
    }  
1
  • 1
    You can use filter insetad of reduce Commented Mar 13, 2018 at 13:21

1 Answer 1

6

The second argument of reduce is the initial value, i.e. the initial value of acc. Since you're calling a push method on acc, it should probably be an array.

When you omit the second argument, the first element in your array is used as the initial value. I.e.: the first call takes (mapMarkers[0], mapMarkers[1]).

To fix this issue, pass a new array to the reduce method:

mapMarkers = mapMarkers.reduce((acc, curr) => {             
  if (curr.sector !== dataSetSector) acc.push(curr);
  return acc;
}, []);
//  ^--- change

Alternatively, as suggested in the comments, you can use filter.

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

2 Comments

Thanks for the response. This works, which is great. But when I log out mapMarkers its showing the entries that should be filtered out not ones I want to keep.
You invert the “selection” by negating your operator: change !== to ===

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.