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

基于经纬度分组保留count最高项的JavaScript数组处理需求

数组去重需求:保留同经纬度下count最高的条目

需求说明

需要处理包含经纬度信息的数组,对于latitud(纬度)和longitud(经度)完全相同的条目,仅保留其中count值最大的那一个,最终生成符合要求的新数组。

原始数组

[
    {
        "color":"green",
        "coment_calification":"Califica",
        "count":7,
        "key":"-13.0711552&-76.3723776&Califica",
        "latitud":"-13.0711552",
        "longitud":"-76.3723776"
    },
    {
        "color":"yellow",
        "coment_calification":"Reporte",
        "count":6,
        "key":"-13.0711552&-76.3723776&Reporte",
        "latitud":"-13.0711552",
        "longitud":"-76.3723776"
    },
    {
        "color":"green",
        "coment_calification":"Califica",
        "count":1,
        "key":"-13.1711552&-76.3423776&Califica",
        "latitud":"-13.1711552",
        "longitud":"-76.3423776"
    },
    {
        "color":"yellow",
        "coment_calification":"Reporte",
        "count":2,
        "key":"-13.1711552&-76.3423776&Reporte",
        "latitud":"-13.1711552",
        "longitud":"-76.3423776"
    }
]

无效代码说明

之前尝试的过滤逻辑无法实现需求,因为e.key == e.key永远为真,相当于未做任何有效过滤:

let result = count.filter((e) => e && e.count && e.key == e.key);
let datas = result;

正确解决方案

通过对象映射+数组遍历的方式实现,核心思路是用经纬度组合作为唯一键,记录每个经纬度下count最大的条目:

// 假设原始数组名为originalArray
const processedMap = {};

originalArray.forEach(item => {
    // 用latitud+longitud拼接成唯一标识键
    const key = `${item.latitud}&${item.longitud}`;
    // 若当前键不存在,或当前条目count大于已存条目count,则更新
    if (!processedMap[key] || item.count > processedMap[key].count) {
        processedMap[key] = item;
    }
});

// 将映射对象的值转为数组,得到最终结果
const finalResult = Object.values(processedMap);

结果示例

运行上述代码后,finalResult的内容为:

[
    {
        "color":"green",
        "coment_calification":"Califica",
        "count":7,
        "key":"-13.0711552&-76.3723776&Califica",
        "latitud":"-13.0711552",
        "longitud":"-76.3723776"
    },
    {
        "color":"yellow",
        "coment_calification":"Reporte",
        "count":2,
        "key":"-13.1711552&-76.3423776&Reporte",
        "latitud":"-13.1711552",
        "longitud":"-76.3423776"
    }
]

逻辑解析

  • 遍历原始数组时,用latitud&longitud拼接成唯一键,确保同经纬度的条目归到同一键下
  • 每次遍历对比当前条目与已存条目的count值,仅保留count更大的条目
  • 最后通过Object.values()将映射对象转为数组,得到去重后的结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:25:45