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
  • 9,711
  • 9
  • 72
  • 108

3 Answers3

3

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
  • 166,183
  • 27
  • 198
  • 186
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
  • 351,820
  • 24
  • 303
  • 358
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
  • 19,906
  • 6
  • 35
  • 55