maudulus
maudulus

Reputation: 11055

Create new array in which items with commas are separated into unique items in the array

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

Upvotes: 2

Views: 148

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386883

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);

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 193338

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);

Upvotes: 4

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22935

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

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

console.log(data);

Upvotes: 0

Related Questions