DEV Community

Austin
Austin

Posted on

Filtering an array of objects by multiple parameters

First, the goods:

function filterByMultipleParams(dataToFilter, paramsToFilterBy) {
if (
typeof paramsToFilterBy === "object" &&
!Array.isArray(paramsToFilterBy) &&
typeof paramsToFilterBy !== null
) {
const filterKeys = Object.keys(paramsToFilterBy);
const filterConditionals = Object.values(paramsToFilterBy);
let filteredData = dataToFilter;
for (let i = 0; i < filterKeys.length; i++) {
filteredData = filteredData.filter(
(row) => row[filterKeys[i]] === filterConditionals[i]
);
}
return filteredData;
} else
console.log("filterParamenters object is required and cannot be empty");
}

Here's a basic codepen example rendering a search into HTML.

This function assumes that you are attempting to filter an array of objects. It requires that the filter parameters be passed in as an object.

To add context, I'm using this to filter CSV data that has been parsed into (you guessed it) an array of objects. The object keys represent the column headers, while the values represent row data.

If you have a cleaner, more efficient version, I'd love to learn it!

Top comments (1)

Collapse
 
austinbagwell profile image
Austin

I love it! Thanks Tony, this is much cleaner!

If I'm reading it right, it is doing the same thing (iterating over the data array and filtering vs. every key/value of the params) but with cleaner syntax?

I haven't used Array.every() before. Gonna have to add that to my toolkit.