Javascript map function to divide comma and store unique values

I have the following display function to remove each item in an object by their comma if it exists.

var items = ['mum, dad', 'uncle, dad', 'brother, sister'];
var clean = [];
clean = items.filter(function(item) {
  return item.split(',');
});

      

The problem is I am not getting the expected result. My conclusion is the clean

same as the output items

. It should look like this:

console.log(items) //  ['mum, dad', 'uncle, dad', 'brother, sister']
console.log(clean) //  ['mum', dad', 'uncle', dad', 'brother', sister']

      

there is one more point, how can I only get unique values, as you can see, after they are comma-spotted some values ​​are repeated, for example dad

how can I store only one?

+3


source to share


3 answers


You can use map()

ES6 instead of filter Set

to only return unique items.

var items = ['mum, dad', 'uncle, dad', 'brother, sister'];
var clean = [...new Set([].concat(...items.map(e => e.split(', '))))]

console.log(clean)
      

Run codeHide result




For IE and other older versions of browsers, you can use this solution.

var items = ['mum, dad', 'uncle, dad', 'brother, sister'];
var clean = [].concat.apply([], items.map(function(e) {
  return e.split(', ');
})).filter(function(e) {
  return !this[e] ? this[e] = 1 : false;
}, {})

console.log(clean)
      

Run codeHide result


+6


source


The filter only returns those items that are true for that particular function. If you want to do some operations / manipulations on each element, you need to go to the map. Try to be as simple as possible, you just have to match each element, split it and then add it to the array clean. Let's take a look at this simple piece of code.



function uniqueArray2(arr) {
    var a = [];
    for (var i=0, l=arr.length; i<l; i++)
        if (a.indexOf(arr[i]) === -1 && arr[i] !== '')
            a.push(arr[i]);
    return a;
}
var items = ['mum, dad', 'uncle, dad', 'brother, sister'];
var clean = [];
items.map(function(item) {
  var splitArray = item.split(',');
  for(var i=0; i<splitArray.length; i++){
    clean.push(splitArray[i]);
  }
});
clean = uniqueArray2(clean);
console.log (clean)
      

Run codeHide result


+2


source


You are using filter

instead map

.

Using map

will return you an array of arrays. If ES6 is not an option, you can concatenate it into one array and remove duplicates like this:

var items = ['mum, dad', 'uncle, dad', 'brother, sister'];
var clean = [];
clean = items.filter(function(item) {
 return item.split(',');
});
var merged = [].concat.apply([], clean);
var unique = arr.filter(function(elem, index, self) {
  return index == self.indexOf(elem);
})

      

0


source







All Articles