I am trying to filter an array of objects, based on the elements within another array.
The array of objects I would like filtered is:
const data = [
{id: 1, method: "bike"},
{id: 2, method: "walk"},
{id: 3, method: "bus"},
{id: 4, method: "bike"},
{id: 5, method: "walk"},
{id: 5, method: "bus"},
]
I have one of three arrays that have what method
I would like to include
const filter1 = ['bike'];
const filter2 = ['bike', 'walk'];
const filter3 = ['bike', 'walk', 'bus'];
I am able to push
the filtered array to a new array, but I would like the filtered array to have the same structure as data
, instead of an array of arrays.
This is my current method, and it gives me a 2D array:
let output = [];
const filterArr = filter2.forEach(element => {
const filt = data.filter(el => el.method === element);
output.push(filt);
});
My desired output is:
const want = [
{id: 1, method: "bike"},
{id: 2, method: "walk"},
{id: 4, method: "bike"},
{id: 5, method: "walk"},
]
CodePudding user response:
I would convert the filter Array
to a Set
, and use the Set.prototype.has
method to check if the current item's method
exists within it.
const filter2 = new Set(['bike', 'walk']);
const data = [
{ id: 1, method: "bike" },
{ id: 2, method: "walk" },
{ id: 3, method: "bus" },
{ id: 4, method: "bike" },
{ id: 5, method: "walk" },
{ id: 5, method: "bus" },
];
const filtered = data.filter(({ method }) => filter2.has(method));
console.log(filtered);
.as-console-wrapper { top: 0; max-height: 100% !important; }
CodePudding user response:
You could take a filter array as methods and check if the method of the data array is included in the filter array.
methods = filter2, // one of your filters.
result = data.filter(({ method }) => methods.includes(method));