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

JavaScript函数开发:验证城市房源计数并筛选达标城市

解决方案

首先明确单个城市的达标条件:

  • 必须包含2居室、3居室、4居室的房源
  • 这三类房源的count值均≥3

基于这个条件,我们可以先写一个辅助函数判断单个城市是否达标,再完成整体的判断和结果返回:

完整代码

function isCityQualified(cityRooms) {
    // 将房源数组转换为以房间数为键的对象,方便快速查找对应房型的count
    const roomCountMap = cityRooms.reduce((map, item) => {
        map[item.rooms] = item.count;
        return map;
    }, {});
    
    // 验证是否存在2、3、4居室,且对应的count都≥3
    return (
        typeof roomCountMap[2] === 'number' && roomCountMap[2] >= 3 &&
        typeof roomCountMap[3] === 'number' && roomCountMap[3] >= 3 &&
        typeof roomCountMap[4] === 'number' && roomCountMap[4] >= 3
    );
}

function checkAllCities(salesData) {
    const allCities = Object.keys(salesData);
    // 筛选出所有达标城市
    const qualifiedCities = allCities.filter(city => isCityQualified(salesData[city]));
    
    // 判断是否所有城市都达标
    const allAreQualified = qualifiedCities.length === allCities.length;
    
    // 按照需求:所有城市达标则返回城市列表,否则返回false(可根据需求调整返回值)
    return allAreQualified ? qualifiedCities : false;
}

测试示例

const sales = {
  "City 1": [
    { "rooms": 1, "count": 1 },
    { "rooms": 2, "count": 2 },
    { "rooms": 3, "count": 3 }
  ],
  "City 2": [
    { "rooms": 1, "count": 1 },
    { "rooms": 2, "count": 1 },
    { "rooms": 3, "count": 1 },
    { "rooms": 4, "count": 2 }
  ],
  "City 3": [
    { "rooms": 2, "count": 6 },
    { "rooms": 4, "count": 7 }
  ],
  "City 4": [
    { "rooms": 1, "count": 4 },
    { "rooms": 2, "count": 6 },
    { "rooms": 3, "count": 3 },
    { "rooms": 4, "count": 7 }
  ]
};

console.log(checkAllCities(sales)); // 输出:false(因为并非所有城市都达标)

对你之前尝试的问题分析

  1. 第一个方案:

    • 没有区分房间类型,错误地检查了所有房型的count,但需求只要求2、3、4居室达标
    • 没有验证是否存在2、3、4居室,就算某个城市缺少其中一类,也可能误判
  2. 第二个方案:

    • isCount使用every检查所有房源的count≥3,错误地限制了1居室的count,而需求中1居室的count不影响结果
    • 逻辑上接近正确,但额外的isCount条件不符合需求,只需单独验证2、3、4居室的count即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 03:10:34