0

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])))
}

1 Answer 1

1

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; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.