【问题标题】:Create new array for each value separated by comma in a string为字符串中以逗号分隔的每个值创建新数组
【发布时间】:2021-01-11 10:01:55
【问题描述】:

输入字符串: "abc def, ghi jkl, mnopq"
所需的输出数组: ["abc","def"] ["ghi","jkl"] ["mnopq"]

输入可以是用空格分隔的短语的任意组合,然后这些短语用逗号分隔。我需要为每个输入字符串创建一个新数组,后跟逗号。创建这些数组时,它们必须用 " " 分割。

以下是使用逗号作为分隔符将字符串拆分为数组值的代码:

str = "abc def, ghi jkl, mnopq";     
const commaSeparatedArray = this.str.split(',').filter(s => s.slice(-1) !== ' ');

console.log(commaSeparatedArray);

不确定下一步是执行此类操作的 for 循环还是 while 循环还是 javascript 原型?

stackblitz 的链接: https://stackblitz.com/edit/angular-ivy-vbdae5?file=src%2Fapp%2Fapp.component.ts

【问题讨论】:

    标签: javascript arrays angular


    【解决方案1】:

    希望对你有所帮助

    var str = "abc def, ghi jkl, mnopq";
    var res = str.split(', ').map(x => x.split(' '));
    console.log(res);

    【讨论】:

      【解决方案2】:

      const str = "abc def, ghi jkl, mnopq";
      
      const commaSeparatedArray = str.split(",");
      
      const result = commaSeparatedArray.reduce((acc, stringWithspaces) => {
        return [...acc, stringWithspaces.split(" ").filter(string=> string)];
      }, []);
      
      console.log(result);

      【讨论】:

        【解决方案3】:

        str = "abc def, ghi jkl, mnopq";
        
        //you need to again split and filter out the empty string to get the desired output.
        
        const commaSeparatedArray = this.str.split(',').map(item => {
          const d = item.split(' ').filter(i => i);
          return [...d]
        })
        console.log(commaSeparatedArray)

        【讨论】:

        • filter 是干什么用的?
        • string 有一个额外的空间,所以当我们使用 split 时,它会给出一个空字符串,以避免我使用了 filter。
        【解决方案4】:

        下面给你一个数组数组。如果您正在寻找类似的东西。

        var s = "abc def, ghi jkl, mnopq";
        var result = s.split(',').map(a=>a.trim().split(' '));
        console.log(result);

        【讨论】:

        • trim() 的好主意?
        • @PramodMali 谢谢,好东西。如果你不介意我问我将如何遍历内部和外部数组说控制台分别记录每个字符串。我试过了:result.forEach(a=>console.log(a));
        • @rkras,您可以使用Array.prototype.flat() 展平结果数组并循环。即result.flat().forEach(a=>console.log(a)。供参考 flat() developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
        【解决方案5】:

        你基本上只想做两轮分裂

        const str = "abc def, ghi jkl, mnopq";
        
        const result = str.split(/,\s*/).map(substr => substr.split(/\s+/))
        
        console.info(result)

        那是

        1. 用逗号 + 零个或多个空格分割字符串
        2. 然后通过在空格上拆分该字符串将每个条目映射到另一个数组

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-02-27
          • 1970-01-01
          • 2019-10-21
          • 1970-01-01
          • 2011-06-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多