0

Let's say I have some code, like this:

const filter = {
      address: 'India',
      name: 'Aleena'
    };

const users = [{
    name: 'John Doe',
    email: '[email protected]',
    age: 25,
    address: 'USA'
  },
  {
    name: 'Aleena',
    email: '[email protected]',
    age: 35,
    address: 'India'
  },
  {
    name: 'Mark Smith',
    email: '[email protected]',
    age: 28,
    address: 'England'
  }
];

const filteredUsers = users.filter((item) => {
  for (var key in filter) {
    if (item[key] === undefined || item[key] != filter[key])
      return false;
  }
  return true;
});

How can I dynamically update/change the filter object to allow users to choose which key:values to use in the filtering process? I know people normally use React for this kind of stuff, but I wondered if there was a "vanilla" way to do it.

1
  • Take input from dropdown via javascript and add some appropriate eventListener on element and store it in variable and pass that variable for filter condition. Commented Sep 26, 2022 at 23:48

3 Answers 3

0

Actually, filter does it for you already. Filter returns a new filtered array without mutating the original array.

"Users" is the original array. "FilteredUsers" is the newly created filtered array off users.

To clone/copy the original Users array above, you can do:

let clonedArray = [...Users]

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

Comments

0

The users array is a perfect candidate for this. Let's say you want to add all of the users ages together. It's pretty cool-simple.

1- function addAges(acc,ele) {return acc + ele.age}

2- Users.reduce(addAges, 0);

That'it. No console.log either. It'll returned the sum

Comments

0

here's a very basic example in CodeSandBox to get an idea of what to do.

I believe it meets the requirements of your question

https://codesandbox.io/s/vanila-js-dynamic-filter-6yhhe6?file=/src/index.js

Comments

Your Answer

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