代码之家  ›  专栏  ›  技术社区  ›  Shahriar

JS将数组元素转换为该数组中的多个元素[重复]

  •  -3
  • Shahriar  · 技术社区  · 4 年前

    我想在JS中将所有带逗号的元素转换为数组中的多个元素。

    ["el1,el2", "el3"] => ["el1", "el2", "el3"]
    

    我该怎么做?

    2 回复  |  直到 4 年前
        1
  •  2
  •   trincot    4 年前

    使用 flatMap 具有 split :

    const result = ["el1,el2", "el3"].flatMap(s => s.split(","));
    
    console.log(result);

    或者,首先连接到一个字符串:

    const result = ["el1,el2", "el3"].join().split(",");
    
    console.log(result);
        2
  •  0
  •   Konrad    4 年前

    flatMap 可以循环浏览每个项目,对其进行更改并将元素展平为一个数组

    ["el1,el2", "el3"].flatMap(v =>
      v.includes(',') // check if element includes ','
      ? v.split(',') // if true - split it into smaller arrays
      : v // if false - just return the string as it was
    )