rago182
rago182

Reputation: 185

JavaScript filter returning true but not filtering

For the past hour I've been struggling to get this following code to work:

  for (let i = 0; i < weekarr.length; i++) {
    if (i - 1 > -1) {
      weekarr[i].forEach(arr => {
        weekarr[i - 1].forEach(p => {
          if (
            arr.html === p.html &&
            !(arr.category === "prehab" && arr.canDo === true)
          ) {
            weekarr[i].filter(p => {
              console.log(p === arr);
              return p === arr;
            });
            // if (i + 1 < 5) weekarr[i + 1].push(arr);
          }
        });
      });
    }
  }

weekarr looks like this:

weekarr

I am basically trying to remove an array item if the previous array contains the same array item (in this case recognized with the html property). Everything works perfectly, except it is simply not filtering. I console logged whether it is returning true or false values when it is supposed to, and it is. Can't seem to figure this one out.

Upvotes: 0

Views: 1644

Answers (2)

Umair Farooq
Umair Farooq

Reputation: 1823

Thats because you are not saving the filter array. The result should be saved to be effective e.g.

weekarr[i] = weekarr[i].filter(p => {
          console.log(p === arr);
          return p === arr;
});

Also check filter for more info

Upvotes: 1

SerShubham
SerShubham

Reputation: 883

The filter function returns a new array. It does not modify the original array. Try storing the result of your filter in a new variable and return that?

const filteredWeakArr = weekarr[i].filter(p => {
   console.log(p === arr);
   return p === arr;
});

Now, filteredWeakArr should have your desired result

Upvotes: 1

Related Questions