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

如何用JavaScript的reduce()提取数组中去重非空的section属性

使用JavaScript的reduce()提取去重且非undefined的section数组

基础实现(适合中小规模数组)

// 示例输入数组
const items = [
  {x: 5, y: 607, width: 782, height: 602, line_width: 3},
  {x: 10, y: 602, width: 772, height: 592, line_width: 3, section: 'TextInstruction'},
  {x: 0, y: 400, size: 18, text: 'This cer...', section: 'TextInstruction'},
  {x: 20, y: 300, section: 'RectangleInstruction'},
  {x: 15, y: 200}
];

const uniqueSections = items.reduce((acc, item) => {
  // 过滤掉undefined的section值
  if (item.section !== undefined) {
    // 检查是否已存在,避免重复添加
    if (!acc.includes(item.section)) {
      acc.push(item.section);
    }
  }
  return acc;
}, []);

console.log(uniqueSections); // 输出: ['TextInstruction', 'RectangleInstruction']

性能优化版(适合大规模数组)

如果处理的数组元素数量较多,用Set来做去重判断效率更高(Set.has()是O(1)时间复杂度,比数组的includes()更高效):

const uniqueSectionsSet = items.reduce((acc, item) => {
  if (item.section !== undefined) {
    acc.add(item.section);
  }
  return acc;
}, new Set());

// 将Set转换为数组
const uniqueSections = Array.from(uniqueSectionsSet);

console.log(uniqueSections); // 输出: ['TextInstruction', 'RectangleInstruction']

逻辑说明

  • 两种实现都通过reduce遍历数组,初始化累加器分别为空数组和空Set
  • 遍历每个对象时,先判断section属性是否存在且不为undefined,过滤无效值
  • 基础版通过数组的includes判断是否重复,优化版利用Set自动去重的特性
  • 最终得到仅包含去重、有效section值的数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:01:22