ash
ash

Reputation: 11

Filter Array with callback function in Javascript

I have an array of object arrayOfUsers as below and i want to filter that dynamically based on the object filterValues. If i remove name from filterValues the code should filter the array with age only and if i add id also to filterValues it should filter the array with three properties with out directly specifying key in the filter code and the key should capture from filterValues. I would like to get a solution for this using callback function. Appreciate for the solutions.

const arrayOfUsers = [
 { id: 1, name: 'Sam', age: 33 },
 { id: 2, name: 'Ram', age: 34 },
 { id: 3, name: 'Raj', age: 32 },
 { id: 4, name: 'Som', age: 2 }]

const filterValues = { name: 'R', age: 3 }

Expected Output:

[
 { id: 2, name: 'Ram', age: 34 },
 { id: 3, name: 'Raj', age: 32 }
]

Here is the sample code where i am stuck on.

const test = (arr) => {
  Object.keys(filterValues).map((key, i) => arr.filter((user) => user[key].includes(key[i])))
}

Upvotes: 0

Views: 62

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386604

You could convert the properties to string and seach for a substring.

const
    arrayOfUsers = [{ id: 1, name: 'Sam', age: 33 }, { id: 2, name: 'Ram', age: 34 }, { id: 3, name: 'Raj', age: 32 }, { id: 4, name: 'Som', age: 2 }],
    filterValues = { name: 'R', age: 3 },
    filters = Object.entries(filterValues),
    result = arrayOfUsers.filter(user => filters.every(([key, value]) =>
        user[key].toString().includes(value)
    ));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions