My goal is to filter an array based on the contents of another array, and here is the code I have written for it.
private get filteredArray() {
const filteredArray = this.unfilteredArray;
console.log(this.unfilteredArray);
filteredArray = this.unfilteredArray.filter(
(p) => this.filteredNumbers.includes(p)
);
return filteredArray;
}
For example, let's say we have two arrays with the following values:
this.unfilteredarray = ["1", "2", "4", "3"]
this.filteredNumbers = ["2"]
The this.filteredNumbers
array contains values selected by the user from a multiple selection box. In this case, the user has selected 2
, and as a result, the function returns an array filteredArray
containing the value "2"
. However, if the user selects another number such that this.filteredNumbers
becomes ["2", "3"]
, the function still only returns "2"
in filteredArray
instead of both 2
and 3
. This issue arises because upon logging, it is observed that after selecting a new filterNumber
for the second time, the unfilteredArray
only retains the value "2"
instead of all its original numbers 1-4. What am I missing here or should I approach this differently?
EDIT: Follow-up question regarding the correct solution If I have an object containing three different arrays that I want to filter simultaneously and then return the object with its filtered arrays intact, how can I achieve that? The code snippet below attempts to do so, but it doesn't work as it alters the original arrays. Would I need to create three separate methods for each array?
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;
}