CodeNewbie Community 🌱


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 (0)