创建新数组,其中带逗号的项目在数组中分成唯一项目 [英] Create new array in which items with commas are separated into unique items in the array
问题描述
我有一个数组,它使用 concat
组合多个数组的源。
I have an array that is combining the sources of multiple arrays using concat
.
var tags = [].concat.apply([], [typeArr,genderArr,conditionArr]);
然后过滤任何
tags = tags.filter(function(entry) { return entry.trim() != ''; });
然而,我意识到,由于数据的来源,有些项目是以字符串形式出现的用逗号,这样标签
数组如下所示: [red,blue,green,yellow,orange,purple ,黑色]
However, I realized that, because of where the data comes from, some items are coming in as strings with commas, such that tags
array looks like the following: ["red","blue","green,yellow,orange","purple,black"]
我如何拆分项目,使标签数组看起来像 [red, 蓝色, 绿色, 黄色, 橙色, 紫色, 黑]
?我在思考我在数组上循环然后使用split将这些重新插入到一个新数组中的东西?
How could I split the items so that the tags array looks like ["red","blue","green","yellow","orange","purple","black"]
? I was thinking something where I loop over the array and then use split to reinsert these into a new array?
我正在尝试使用vanilla JavaScript
I'm trying to do it with vanilla JavaScript
推荐答案
使用 .toString() Array.join()
Array.split()
用逗号来获取单个项目的数组:
Use Array.join()
by comma (or .toString()
which does the same) to convert the array to a single string, the use Array.split()
by comma to get an array of individual items:
var arr = ["red","blue","green,yellow,orange","purple,black"];
var result = arr.join(',').split(',');
console.log(result);
这篇关于创建新数组,其中带逗号的项目在数组中分成唯一项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!