[英]Filter with "&&" condition in array.filter()
所以人们我有 3 个复选框:
<label>
<input type="checkbox" value="Java" id="check-java" class="check-java filled-in"
/>
<span>Java</span>
</label>
<label>
<input type="checkbox" value="JavaScript" id="check-javascript" class="check-javascript filled-in" />
<span>JavaScript</span>
</label>
<label>
<input type="checkbox" value="Python" id="check-python" class="check-python filled-in"
/>
<span>Python</span>
</label>
当用户选择此复选框时,我会在 eventListener` 中捕获它:
const checkBoxes = document.querySelectorAll('input[type=checkbox]');
checkBoxes.forEach((box) => {
return box.addEventListener('change', filterByCheckBox)
});
因此,当用户选择两个或多个此复选框时,我需要过滤一个数组 (devsFiltered),其中包含一个名为“programmingLanguages”的子数组,在此数组中我有 3 个可能的值“Java、JavaScript 或 Python”,并且我仅当数组包含复选框选择的两个或多个值时才需要过滤,我尝试使用的代码是:
function filterByCheckBox(e) {
const checkOption = e.target.value;
if (devsFiltered.length > 0) {
const filtered = devsFiltered
.filter(item => item.programmingLanguages
.every(lang => lang.language == checkOption));
mapUsers(filtered)
}
}
您需要获取所有选择,并且需要查看是否所有选中的项目都在数组中。
var people = [ { name: "w", codes : ['a', 'b'] }, { name: "x", codes : ['a', 'c'] }, { name: "y", codes : ['a', 'b'] }, { name: "z", codes : ['b','c'] } ]; var form = document.querySelector("form"); form.addEventListener("change", function() { // get all the checked checkboxes const selections = document.querySelectorAll('[type="checkbox"]:checked'); // get all their values const values = selections && [...selections].map(({ value }) => value); // filter the list to make sure all the values are in the object const filtered = values ? people.filter(({ codes }) => values.every(code => codes.includes(code))) : people; // Just to display something console.log(filtered.map(f => f.name).join(",")); });
<form id="form"> <label for="a">A</label><input type="checkbox" id="a" value="a" /> <label for="b">B</label><input type="checkbox" id="b" value="b" /> <label for="c">C</label><input type="checkbox" id="c" value="c" /> </form>
以一种更具可读性的格式
您需要获取所有选择,并且需要查看是否所有选中的项目都在数组中。
var people = [ { name: "w", codes : ['a', 'b'] }, { name: "x", codes : ['a', 'c'] }, { name: "y", codes : ['a', 'b'] }, { name: "z", codes : ['b','c'] } ]; var form = document.querySelector("form"); form.addEventListener("change", function() { let filtered = people; const selections = document.querySelectorAll('[type="checkbox"]:checked'); if (selections) { const values = [...selections].map(x => x.value); filtered = people.filter(person => values.every(code => person.codes.includes(code) ) ) } // Just to display something console.log(filtered.map(f => f.name).join(",")); });
<form id="form"> <label for="a">A</label><input type="checkbox" id="a" value="a" /> <label for="b">B</label><input type="checkbox" id="b" value="b" /> <label for="c">C</label><input type="checkbox" id="c" value="c" /> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.