JavaScript Filter Array Multiple Conditions

javascript filter array multiple conditions

You can do like this

var filter = {  address: 'England',  name: 'Mark'};var users = [{    name: 'John',    email: 'johnson@mail.com',    age: 25,    address: 'USA'  },  {    name: 'Tom',    email: 'tom@mail.com',    age: 35,    address: 'England'  },  {    name: 'Mark',    email: 'mark@mail.com',    age: 28,    address: 'England'  }];

users= users.filter(function(item) { for (var key in filter) { if (item[key] === undefined || item[key] != filter[key]) return false; } return true;});
console.log(users)

Filter Array with multiple conditions in other array of options

I don't think flattening the filters is the right idea, because then you'll be mixing the different properties. Iterate over the filters object instead, and have the item pass the test if, for every filter property:

  • the filter is empty, or
  • the same property on the object being iterated over exists in the filter array

const data = [
{id: 1, name: 'john', location: 'NY', age: '50'},
{id: 2, name: 'mj', location: 'LA', age: '41'},
{id: 3, name: 'mike', location: 'LA', age: '50'},
{id: 4, name: 'lebron', location: 'SF', age: '20'},
{id: 5, name: 'mike', location: 'NY', age: '60'},
{id: 6, name: 'john', location: 'MI', age: '30'},
{id: 7, name: 'mj', location: 'NY', age: '53'}
];
const filters = {
name: ['mike', 'mj'],
location: ['NY'],
age: []
};

const filtered = data.filter(obj =>
Object.entries(filters).every(([key, filterArr]) => (
filterArr.length === 0 || filterArr.includes(obj[key])
))
);
console.log(filtered);

Filtering array data with multiple conditions with ES6

I'm not sure I fully understand the goal you want to achieve, but I think you've made a logical error.

First, you used the or operator in your statement. It checks whether at least one of the conditions is true. So you first check if the f[0] includes the searchString and if it doesn't it proceeds to the second statement.

Second, you check if the searchFilter is empty and if it does, you check if the f[1] type is equal to a11yType.

And this works just like you described it. You can only filter by the search phrase or by the a11yType if the search phrase is empty.

So if you want to combine two filters (check what results include a searchString and have a matching a11yType), just try this:

f[0].includes(searchFilter.toUpperCase())
&& // only if the search string is contained in f[0]
(a11yType === '' || f[1].type === a11yType) // a11yType is empty or the result satisfies the filter

Filter array of object based on multiple conditions in React

The issue is that you are applying all of your filters instead of just ones that are defined. And also you also should just return false from your filters if they are defined, that is the only way to run through all of them. So your code should look something like this

const filteredAllPersons = oldPersons.filter(person => {
if (genderFilter && person.gender !== genderFilter) {
return false
}
// apply all other filters the same as above

// Finally return true because record has satisfied all conditions
return true
})

How to filter array of objects on multiple conditions and add exception?

I kept the filtering part you implemented as an intermediate output. using that i got a count for each id. then using that i filtered out from the intermediate array where if the has count > 1 and has a null name i remove it.

 const data = [{id: 1234,name: "Name1"},{id: 1234,name: "Name1"},{id: 1234,name: "Name2"},{id: 1234,name: null},{id: 5678,name: "Name3"},{
id: 5678,name: "Name3"},{id: 5678,name: null},{id: 9999,name: null},{id: 9999,name: null},];

//filtering out duplicates
let a = data.filter((value, index, self) => {
return (
self.findIndex(
(v) =>
v.id === value.id &&
v.name=== value.name
) === index
);
});

//get count for ids in partially filtered
let idcount = a.reduce((acc,curr) => {
if(!acc[curr.id])acc[curr.id] = 0
acc[curr.id] += 1
return acc;
},{})

//remove the duplicate nulls
let final = a.filter((el) => {
return !(idcount[el.id]>1 && el.name===null)
})

console.log(final)

JavaScript multiple condition filtering with array of conditions?

You can use a higher order filter function to handle applying filter conditions and is passed to your array.prototype.filter function.

const filterData = ({ filters = [], every = false }) => (el) =>
filters[every ? "every" : "some"]((filterFn) => filterFn(el));

This consumes an options object that defines an array of filter condition functions that accept a single element value/object from your data array and returns the function used for the array filtering.

Example:

// AC AND nonAC
data.filter(filterData({
filters: [
({ AC, nonAC }) => AC && nonAC,
],
}))

Edit javascript-multiple-condition-filtering-with-array-of-conditions

Note

If your data is in the form

"AC": "false"

Where the booleans are stringified then make the following adjustment to your condition checkers, compare to === 'true':

({ AC, nonAC }) => AC === "true" || nonAC === "true"

Edit

After discussion it seems some of these conditions are not mutually inclusive, or rather, they are only mutually inclusive in specific groups.

Still using a Higher Order Function, the logic is tweaked a bit to consume the array of key-value conditions.

Create a mapping function to map your user selected filters ([{ AC: "true" }, ...]) to a groups of "filterBy" values that are mutually inclusive. These will be logical OR'd (||) together while the sets will be exclusive by using logical AND'd (&&) together.

const mapfiltersToSets = (filters) => {
const filtersObject = filters.reduce((conditions, condition) => {
const [key, value] = Object.entries(condition).pop();

switch (key) {
case "AC":
case "nonAC":
return {
...conditions,
acConditions: [...(conditions.acConditions || []), { key, value }]
};

case "seater":
case "sleeper":
return {
...conditions,
seatSleeper: [...(conditions.seatSleeper || []), { key, value }]
};

// add new AND groups here

default:
return conditions;
}
}, {});
return Object.values(filtersObject);
};

const filterData = (filters = []) => (el) =>
mapfiltersToSets(filters).every((filterSet) =>
filterSet.some(({ key, value }) => el[key] === value)
);

Example:

// AC AND nonAC
data.filter(filterData([{ AC: "true" }, { nonAC: "true" }]))

Demo with extended dataset and unit tests. Good start to build from.

Edit javascript-multiple-condition-filtering-with-array-of-conditions (forked)

How to filter array with multiple conditions in Vuejs?

try like following snippet:

const app = new Vue ({
el: '#app',
data() {
return {
search: '',
itemsList: [],
isLoaded: false,
selectNum: '',
userList: [
{
id: 1,
name: "Prem",
status:"ok"
},
{
id: 2,
name: "Chandu",
status:"notok"
},
{
id: 3,
name: "Shravya",
status:"ok"
},
{
id: 4,
name: "kirt",
status:"notok"
}
]
}
},
created(){
this.isLoaded = true;
},
computed: {
filteredAndSorted(){
function compare(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
const res = this.userList.filter(user => {
return user.name.toLowerCase().includes(this.search.toLowerCase())
}).sort(compare)
if (this.selectNum) {
return res.filter(user => user.status === this.selectNum )
}
return res
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-if="isLoaded">
<select v-model="selectNum" name="text">
<option value="" selected="selected">Select status</option>
<option value="ok">ok</option>
<option value="notok">notok</option>
</select>
</div>
<div class="search-wrapper">
<input type="text" v-model="search" placeholder="Search title.."/>
<label>Search Users:</label>
</div>
<ul>
<li v-for="user in filteredAndSorted">{{user.name}}</li>
</ul>
</div>


Related Topics



Leave a reply



Submit