2

I have an array that is combining the sources of multiple arrays using concat.

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

The items in the array are then filtered for any

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

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"]

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?

I'm trying to do it with vanilla JavaScript

maudulus
  • 10,627
  • 10
  • 78
  • 117

3 Answers3

4

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);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
2

You could use a Set for getting unique values after the values 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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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

data = data.reduce(function(prev, next) {
    return prev.concat(next.split(','));
}, []);

console.log(data);
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60