Home > Enterprise >  How to update filter array without using React?
How to update filter array without using React?

Time:09-27

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.

CodePudding user response:

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]

CodePudding user response:

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

CodePudding user response:

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

  • Related