Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using split function to output distinct values

I have the following array:

var fruits = ["orange","orange,apple","apple,orange,pear"];

I am trying to achieve the following:

fruits = ["orange","apple","pear"]

Any suggestions, thanks!

like image 282
Bob the Builder Avatar asked Dec 12 '25 05:12

Bob the Builder


1 Answers

Here's one way to do it:

fruits = fruits.reduce(function (p, c) {
    return p.concat(c.split(","));
}, []).filter(function(e, i, a) {
    return a.indexOf(e) === i;
});

(EDIT: Note that .filter() and .reduce() are not supported in IE8 or older, but there are shims available if you need to support older IE.)

like image 164
nnnnnn Avatar answered Dec 13 '25 18:12

nnnnnn