You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何按数值范围属性过滤对象数组

价格区间筛选课程实现方案

数据结构参考

你定义的课程数组格式如下,prices字段第一个值为区间下限,第二个为区间上限,null代表对应方向无价格限制:

const courses = [
  { name: "Courses in England",    prices: [   0,  100] },
  { name: "Courses in Germany",    prices: [ 500, null] },
  { name: "Courses in Italy",      prices: [ 100,  200] },
  { name: "Courses in Russia",     prices: [null,  400] },
  { name: "Courses in China",      prices: [  50,  250] },
  { name: "Courses in USA",        prices: [ 200, null] },
  { name: "Courses in Kazakhstan", prices: [  56,  324] },
  { name: "Courses in France",     prices: [null, null] },
];

筛选逻辑

核心判断规则:传入目标价格后,返回价格区间覆盖该值(包含边界)的课程,边界处理规则:

  • 下限为null时,视为价格下限无限制(等价于负无穷)
  • 上限为null时,视为价格上限无限制(等价于正无穷)
  • 目标值满足 区间下限 <= 目标值 <= 区间上限 即判定为匹配

若你需要排除存在null边界的课程,只需要在判断条件中额外增加上下限非空校验即可。

代码实现

基于filter方法实现(和你之前按名称筛选的写法一致)

function filterByPrice(courseList, targetPrice) {
  return courseList.filter(course => {
    const [min, max] = course.prices;
    const realMin = min === null ? -Infinity : min;
    const realMax = max === null ? Infinity : max;
    return targetPrice >= realMin && targetPrice <= realMax;
  });
}

// 测试:传入价格100
console.log(filterByPrice(courses, 100));

基于for循环实现(和你之前写的遍历逻辑一致)

function filterByPrice(courseList, targetPrice) {
  const matched = [];
  for (let i = 0; i < courseList.length; i++) {
    const course = courseList[i];
    const [min, max] = course.prices;
    const realMin = min === null ? -Infinity : min;
    const realMax = max === null ? Infinity : max;
    if (targetPrice >= realMin && targetPrice <= realMax) {
      matched.push(course);
    }
  }
  return matched;
}

// 测试
console.log(filterByPrice(courses, 100));

自定义调整

如果需要排除带null边界的课程,只需要把判断条件修改为:

return min !== null && max !== null && targetPrice >= min && targetPrice <= max;

此时传入100会返回英格兰、意大利、中国、哈萨克斯坦四个结果,你举例时遗漏了价格区间为[50,250]的中国课程,该课程实际也符合区间覆盖100的规则。

内容的提问来源于stack exchange,提问作者nazonstack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 04:31:11