admin管理员组文章数量:1391925
This is a simplified example of a problem I have on a website.
I have an array with some items like this:
var testArr = ["Jeremy", "John", "Hank", "Hal"];
If I know what the filters are, I can filter it like this:
var testArr2 = testArr.filter(function (item){
return item.length < 5 &&
item.startsWith("H");
});
On my website, I have an interface where the user can select several filters. In this example, the user would be able to decide to filter by either length or what the value starts with. I need to be able to add conditions to that return
dynamically or find some other way to filter. I tried some of the answers at he SO thread javascript filter array multiple conditions, but I am having trouble applying that to my example.
Thanks in advance!
This is a simplified example of a problem I have on a website.
I have an array with some items like this:
var testArr = ["Jeremy", "John", "Hank", "Hal"];
If I know what the filters are, I can filter it like this:
var testArr2 = testArr.filter(function (item){
return item.length < 5 &&
item.startsWith("H");
});
On my website, I have an interface where the user can select several filters. In this example, the user would be able to decide to filter by either length or what the value starts with. I need to be able to add conditions to that return
dynamically or find some other way to filter. I tried some of the answers at he SO thread javascript filter array multiple conditions, but I am having trouble applying that to my example.
Thanks in advance!
Share Improve this question asked Jan 6, 2020 at 14:58 mrcoulsonmrcoulson 1,4036 gold badges22 silver badges35 bronze badges 3- Use code to the effect of "My filter is empty or item starts with my filter." – Robert Harvey Commented Jan 6, 2020 at 15:00
- Only you can come up with the code for this, but it sounds like you need some booleans? – Lightness Races in Orbit Commented Jan 6, 2020 at 15:01
- 1 Thanks to everyone who responded to this question! I learned something from every answer offered. This is why SO is an awesome resource. – mrcoulson Commented Jan 6, 2020 at 16:18
6 Answers
Reset to default 20You could store the single filters in an array as function and filter by checking each filter function with the actual value.
var array = ["Jeremy", "John", "Hank", "Hal", "Hermine"],
filters = {
smallerThanFive: item => item.length < 5,
startsWithH: item => item.startsWith('H')
}
selected = [filters.smallerThanFive, filters.startsWithH],
result = array.filter(item => selected.every(f => f(item)));
console.log(result);
Can't you just ask the user the two parameters, the length and the starting value, storing them in two variables and then using them as the values for the filter() function?
Something like this:
var maxLength = userLengthInput; //Get this value from the user.
var startValue = userStartValueInput; //Get this value from the user.
var testArr2 = testArr.filter(function (item){
return item.length < maxLength && item.startsWith(startValue);
});
You could isolate the cases and return true or false individually, or you can combine all conditions into one big boolean expression.
For example:
var testArr2 = testArr.filter(function (item){
if (checkBoxCheckedForRejectStringWithJustOneCharacter() &&
item.length === 1) return false;
if (checkBoxCheckedForAcceptingAllStringsBeginningWithZ() &&
item[0].toLowerCase() === "z") return true;
return item.length < 5 &&
item.startsWith("H");
});
It just depends on your UI and you can customize the conditions in your code.
Just ask.
const testArr = ["Jeremy", "John", "Hank", "Hal"];
const filterIt = (arr,len,sw) => {
return arr.filter(item => {
let okLength = len === null || (len && len > 0 && item.length<len);
let okSw = !sw || (sw && item.startsWith(sw));
return okLength && okSw;
})
}
console.log(filterIt(testArr,null,"H"))
console.log(filterIt(testArr,5))
console.log(filterIt(testArr,4,"H"))
For simple usage it's better to have a class Filter
containing all filtering logic. Then instantiate it with filters we want and apply them to the input we already have.
Take a look at the code below. It's more readable.
For the sake of extendability, you can also put all filtering logics into individual class and just use those classes in your main Filter
class.
var testArr = ["Jeremy", "John", "Hank", "Hal"];
function Filter(filters) {
this.filters = filters;
}
Filter.prototype.filterByLength = function(items, value) {
return items.filter(function(item) {
return item.length < value
})
};
Filter.prototype.filterByValue = function(items, value) {
return items.filter(function(item) {
return item.startsWith(value);
})
};
Filter.prototype.filter = function(items) {
return Object.entries(this.filters)
.reduce(function (final, [key, value]) {
return final && this[key](items, value)
}.bind(this), true)
};
var instance = new Filter({
filterByLength: 5,
filterByValue: 'H'
})
var result = instance.filter(testArr)
console.log(result)
Here an example with HTML/CSS/JS:
https://codepen.io/Karkael/pen/zYxpWqR
function showFilteredList() {
var filterLength = formFilter["string-length"].value;
var filterStarts = formFilter["string-starts"].value;
showList(testArr.filter(function (item) {
if (filterLength.length && item.length >= parseInt(filterLength)) return false;
if (filterStarts.length && !item.startsWith(filterStarts)) return false;
return true;
}));
}
Hope it helps you!
本文标签: In JavaScripthow can I filter an array with dynamic conditionsStack Overflow
版权声明:本文标题:In JavaScript, how can I filter an array with dynamic conditions? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738637530a2104122.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论