0

So what I am trying to do is filter an array based on contents of another array so this is the code I have.

private get filteredArray() {
  const filteredArray = this.unfilteredArray;
  console.log(this.unfilteredArray);

  filteredArray = this.unfilteredArray.filter(
    (p) => this.filteredNumbers.includes(p)
  );
  return filteredArray;
}

So for example we have the 2 arrays with values

this.unfilteredarray = ["1", "2", "4", "3"]
this.filteredNumbers = ["2"]

this.filteredNumbers gets values from a multiple selection box so here the user selected 2 and for this it works the item that is returned from the function is an array filteredArray with the value "2". But when I then choose another number to filter on so this.filteredNumbers looks like ["2", "3"] then I still only get filteredArray with value "2" back when I expect to get 2 and 3 back. This seems to be because on the console.log I can see that when I choose an filterNumber for the second time the unfilteredArray only has the value "2" left in it when it should still hold all its original numbers 1-4. What am I missing here or should I do this in some other way?

EDIT: followup question to correct answer So if i had an object that among all its props has 3 different arrays that i want to filter them all and then return the object itself with its filtered arrays. Kind of like this but this ofc doesnt work as it will mess up the original array. Or would i need 3 different get?

private get filteredObject() {
   this.object.unfilteredArray.filter(
    (p) => this.filteredNumbers.includes(p)
  );
   this.object.unfilteredArrayTwo.filter(
    (p) => this.filteredNumbers.includes(p)
  );
   this.object.unfilteredArrayThree.filter(
    (p) => this.filteredNumbers.includes(p)
  );
  return object;
}

1 Answer 1

1

const filteredArray = this.unfilteredArray; doesn't clone the array as you want it just references the array which will be overridden when you do :

  filteredArray = this.unfilteredArray.filter(
    (p) => this.filteredNumbers.includes(p)
  );

which means that filteredArray and this.unfilteredArray refer to the same data.

to avoid this just return the filtered array with creating a temporary one :

private get filteredArray() {
   return this.unfilteredArray.filter(
    (p) => this.filteredNumbers.includes(p)
  );
  
}
Sign up to request clarification or add additional context in comments.

Comments

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.