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

如何过滤含相同Id不同type的对象数组:保留HD类型

解决方案:过滤重复ID并保留HD类型条目

问题分析

需求核心:数组中若存在相同id的条目,保留type为HD的、移除type为SD的;若某个id仅存在SD条目,则保留该条目。

你的尝试代码问题

你写的findIndex回调里三元运算符语法错误,且逻辑未正确覆盖优先级判断,导致过滤失效。

方法一:对象映射(高效易读)

通过遍历数组,用id作为键存储条目,遇到相同id时优先保留HD类型,最后将对象值转为数组即可:

const arr = [
    { id: "123", type: "HD" },
    { id: "123", type: "SD" },
    { id: "1234", type: "HD" },
    { id: "12", type: "SD" },
];

const idMap = {};
for (const item of arr) {
    // 若当前id未存储,或已存的是SD类型,则替换为当前项(HD优先级更高)
    if (!idMap[item.id] || idMap[item.id].type === "SD") {
        idMap[item.id] = item;
    }
}

const filteredArr = Object.values(idMap);
console.log(filteredArr);
// 输出:[{id: "123", type: "HD"}, {id: "1234", type: "HD"}, {id: "12", type: "SD"}]

方法二:改进filter+findIndex写法

修复你原有的逻辑,确保每个条目要么是当前id下首个HD,要么是无HD时的首个SD:

const filteredArr = arr.filter((a, index, tmp) => {
    // 查找当前id的首个HD条目索引
    const hdItemIndex = tmp.findIndex(b => b.id === a.id && b.type === "HD");
    // 满足两种情况则保留:当前是HD且是首个HD;或当前id无HD,且当前是首个条目
    return (a.type === "HD" && hdItemIndex === index) || (hdItemIndex === -1 && tmp.findIndex(b => b.id === a.id) === index);
});

console.log(filteredArr);
// 输出结果与方法一一致

方法三:reduce函数式风格

用reduce构建结果数组,动态判断是否添加或替换条目:

const filteredArr = arr.reduce((result, current) => {
    // 检查结果中是否已有当前id的HD条目
    const hasHD = result.some(item => item.id === current.id && item.type === "HD");
    if (!hasHD) {
        const existingSDIndex = result.findIndex(item => item.id === current.id && item.type === "SD");
        if (existingSDIndex === -1) {
            result.push(current);
        } else if (current.type === "HD") {
            // 用HD替换已存在的SD条目
            result[existingSDIndex] = current;
        }
    }
    return result;
}, []);

console.log(filteredArr);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:37:49