【问题标题】:Create new array in which items with commas are separated into unique items in the array创建新数组,其中带有逗号的项目被分隔为数组中的唯一项目
【发布时间】:2018-05-08 17:30:21
【问题描述】:

我有一个数组,它使用concat 组合多个数组的源。

var tags = [].concat.apply([], [typeArr,genderArr,conditionArr]);

然后对数组中的项目进行任何过滤

  tags = tags.filter(function(entry) { return entry.trim() != ''; });

但是,我意识到,由于数据的来源,一些项目以带逗号的字符串形式出现,因此 tags 数组如下所示:["red","blue","green,yellow,orange","purple,black"]

如何拆分项目以使标签数组看起来像["red","blue","green","yellow","orange","purple","black"]?我在想什么我在数组上循环然后使用 split 将它们重新插入到一个新数组中?

我正在尝试使用原生 JavaScript 来实现

【问题讨论】:

标签: javascript arrays


【解决方案1】:

使用Array.join() by comma(或.toString() 也一样)将数组转换为单个字符串,使用Array.split() by comma 获得单个项目的数组:

var arr = ["red","blue","green,yellow,orange","purple,black"];

var result = arr.join(',').split(',');

console.log(result);

【讨论】:

  • 你可以使用join(),因为默认是逗号。
【解决方案2】:

您可以使用Setvalues have been separated 之后获取唯一值

var array = ["red", "blue", "green,yellow,orange", "purple,black", "green,red"],
    result = Array.from(new Set(array.join(',').split(',')));

console.log(result);

【讨论】:

    【解决方案3】:

    var data = ["red","blue","green,yellow,orange","purple,black"];
    
    data = data.reduce(function(prev, next) {
        return prev.concat(next.split(','));
    }, []);
    
    console.log(data);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-08
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多