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

如何在二维数组中统计JSON列表标签频次并更新计数?

标签计数统计实现方案

需求说明

遍历给定的JSON列表集合,完成标签计数统计:

  • 若标签已在taglist中,对应计数递增
  • 若标签不在taglist中,新增该标签并将计数设为1
  • ALL标签的计数需等于总列表条目数(最终为3)

原始数据

JSON列表:

var jsonListings = [
    {
        "img":      "2521",
        "text":     "Alice",
        "tags":     ["structure"]
    },{
        "img":      "2522",
        "text":     "Bob",
        "tags":     ["landscape","FRAMED"]
    },{
        "img":      "2523",
        "text":     "Charlie",
        "tags":     ["structure","MATTED"]
    }
];

初始标签统计数组:

var taglist = [
    ["ALL",0],
    ["FRAMED",0],
    ["MATTED",0]
];

实现代码

// 直接设置ALL标签计数为总列表数
taglist[0][1] = jsonListings.length;

// 遍历每个列表项
$.each(jsonListings, function(index, item) {
    // 遍历当前项的所有标签
    $.each(item.tags, function(tagIndex, tag) {
        // 查找当前标签是否已在taglist中
        var existingTag = $.grep(taglist, function(tagItem) {
            return tagItem[0] === tag;
        });
        
        if (existingTag.length > 0) {
            // 标签存在,递增计数
            existingTag[0][1]++;
        } else {
            // 标签不存在,新增条目
            taglist.push([tag, 1]);
        }
    });
});

// 输出结果,与预期一致
console.log(taglist);

逻辑说明

  1. ALL标签计数:直接赋值为jsonListings.length,无需遍历统计,高效简洁。
  2. 标签遍历与查找:
    • 外层遍历每个列表条目,内层遍历条目下的所有标签
    • 用$.grep在taglist中匹配当前标签,找到则递增计数
    • 未匹配到则新增[标签名, 1]格式的条目到taglist
  3. 最终taglist会生成预期的结果:
    [
        ["ALL", 3],
        ["FRAMED",1],
        ["MATTED",1],
        ["structure",2],
        ["landscape",1]
    ]
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:03:15