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

3
  • 1
    "I was thinking something where I loop over the array and then use split to reinsert these into a new array". Sounds like good thinking. Have you tried it? What seems to not be working here that this post exists? Commented May 8, 2018 at 17:32
  • stackoverflow.com/q/42391430 Commented May 8, 2018 at 17:40
  • stackoverflow.com/a/43528397 Commented May 8, 2018 at 17:40

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

You can use join(), since the default is a comma.
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);

Comments

0

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

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

console.log(data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.