如何解决Javascript过滤数组以给出两个范围参数的子集
如何过滤两个数组,使我得到两个范围重叠产生的子集?
例如,假设这是我的带有一堆对象的数组:
const list = [{
id: 1,price: "10",weight: "19.45"
},{
id: 2,price: "14",weight: "27.8"
},{
id: 3,price: "45",weight: "65.7"
},{
id: 4,price: "37",weight: "120.5"
},{
id: 5,price: "65",weight: "26.9"
},{
id: 6,price: "120",weight: "19.3"
},{
id: 7,price: "20",weight: "45.7"
}]
现在,我要根据两个参数price
和weight
的范围来过滤上述对象数组。
let range = {
startPrice: 15,endPrice: 60,startWeight: 22.0,endWeight: 70.5,}
我想用这些范围参数过滤列表,这将返回一个数组,其中包含满足两个过滤范围的对象子集。因此,输出数组应为:
filtered = [{
id: 3,weight: "45.7"
}]
因为带有id: 3
和id: 5
的项目满足两个范围的子集。我的list.filter()
函数应如何显示?非常感谢您的帮助。
解决方法
您的意思是3和7
此外,您需要删除引号或将其强制转换为数字。请注意,过滤器将期望布尔测试为true或false就足够了。否,是否需要
const list = [{ id: 1,price: "10",weight: "19.45" },{ id: 2,price: "14",weight: "27.8" },{ id: 3,price: "45",weight: "65.7" },{ id: 4,price: "37",weight: "120.5" },{ id: 5,price: "65",weight: "26.9" },{ id: 6,price: "120",weight: "19.3" },{ id: 7,price: "20",weight: "45.7" }];
let range = { startPrice: 15,endPrice: 60,startWeight: 22.0,endWeight: 70.5,}
const res = list.filter(item =>
+item.price >= range.startPrice &&
+item.price <= range.endPrice &&
+item.weight >= range.startWeight &&
+item.weight <= range.endWeight);
console.log(res);
,
注意:我使用String
是因为值存储为Number
。还有其他方法可以从String
中提取var list = [{"id":1,"price":"10","weight":"19.45"},{"id":2,"price":"14","weight":"27.8"},{"id":3,"price":"45","weight":"65.7"},{"id":4,"price":"37","weight":"120.5"},{"id":5,"price":"65","weight":"26.9"},{"id":6,"price":"120","weight":"19.3"},{"id":7,"price":"20","weight":"45.7"}];
var range = {
startPrice: 15,endWeight: 70.5
};
var filtered=list.filter(
element=> {
var elementprice=parseFloat(element.price);
var elementweight=parseFloat(element.weight);
if(
elementprice>=range.startPrice &&
elementprice<=range.endPrice &&
elementweight>=range.startWeight &&
elementweight<=range.endWeight
) {
return true;
}
return false;
}
);
console.log(filtered);
。
.as-console-wrapper { max-height: 100% !important; top: 0; }
python
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。