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

如何从含字符串数组的对象数组中提取去重的单一字符串数组?

解决方法

方法一:flatMap + Set(最简洁)

先通过flatMap提取所有嵌套数组的元素并扁平化,再用Set自动去重,最后转回数组:

const input = [
  { array_of_strings: ['string1', 'string2', 'string3'] },
  { array_of_strings: ['string1', 'string4', 'string5'] },
  { array_of_strings: ['string6', 'string3', 'string2'] }
];

const uniqueStrings = [...new Set(input.flatMap(item => item.array_of_strings))];
console.log(uniqueStrings);
// 输出: ['string1', 'string2', 'string3', 'string4', 'string5', 'string6']
  • flatMap(item => item.array_of_strings):遍历每个对象,提取array_of_strings数组并自动展开为一维数组,得到['string1','string2','string3','string1','string4','string5','string6','string3','string2']
  • new Set(...):利用Set的唯一性自动去除重复元素
  • [...Set]:将Set转换回数组格式

方法二:reduce手动扁平化 + Set

如果需要更直观的扁平化过程,可以用reduce先拼接所有数组元素,再去重:

const input = [
  { array_of_strings: ['string1', 'string2', 'string3'] },
  { array_of_strings: ['string1', 'string4', 'string5'] },
  { array_of_strings: ['string6', 'string3', 'string2'] }
];

// 先扁平化数组
const flattened = input.reduce((acc, current) => {
  acc.push(...current.array_of_strings);
  return acc;
}, []);

// 再去重
const uniqueStrings = [...new Set(flattened)];
console.log(uniqueStrings);

方法三:filter手动去重(无需Set)

如果不想用Set,也可以用filter结合indexOf实现去重,适合需要兼容旧环境的场景:

const input = [
  { array_of_strings: ['string1', 'string2', 'string3'] },
  { array_of_strings: ['string1', 'string4', 'string5'] },
  { array_of_strings: ['string6', 'string3', 'string2'] }
];

const flattened = input.flatMap(item => item.array_of_strings);
const uniqueStrings = flattened.filter((str, idx) => flattened.indexOf(str) === idx);
console.log(uniqueStrings);
  • flattened.indexOf(str) === idx:只保留当前元素第一次出现的实例,后续重复元素会被过滤掉

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 12:10:23