Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – Use elements in array to filter array of objects

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"},
]

>Solution :

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading