Reputation: 87
I am attempting to scan through and remove any duplicates from a string.
Here is an example scenario:
var str = "Z80.8, Z70.0, Z80.8";
The goal is to pass str
into a function and have it returned as "Z80.8, Z70.0"
The string is separated by commas.
Upvotes: 2
Views: 535
Reputation: 358
Javascript code splits the string on ", "
then defines an anonymous function passed to filter, that takes three parameters representing the item, index and allitems. The anonymous function returns true if the index of this item is the same as the first index of that item found, otherwise false. Then join the elements of the Arrray on comma.
var str = "Z80.8, Z70.0, Z80.8";
var res = str.split(", ").filter(function(item,index,allItems){
return index == allItems.indexOf(item);
}).join(', ');
console.log(res);
Result:
Z80.8, Z70.0
Upvotes: 1
Reputation: 36564
You can convert string
to array
using split()
and then convert it to Set and then again join()
it
var str = "Z80.8, Z70.0, Z80.8";
str = [... new Set(str.split(', '))].join(', ')
console.log(str);
Upvotes: 0
Reputation: 9174
let str = "Z80.8, Z70.0, Z80.8";
let uniq = [...new Set(str.split(", "))].join(", ");
Upvotes: 0
Reputation: 2664
Use something like:
str
.split(',')
.map(function(s) { return s.trim() })
.filter(function(v, i, a) { return a.indexOf(v) === i })
.join(', ');
Upvotes: 4
Reputation: 1894
I suggest to split this into an array then remove duplicates.
var arr = str.replace(" ", "").split(",");
var uniqueArray = arr.filter((v, i, arr) => arr.indexOf(v) === i);
Upvotes: -1
Reputation: 751
Try this:
let str = "Z80.8, Z70.0, Z80.8";
str = [...new Set(str.split(", "))].join(", ");
console.log(str);
Upvotes: 0
Reputation: 17606
Use regex to get each value and then use Set to remove duplicates.
const data = "Z80.8, Z70.0, Z80.8";
const res = [...new Set(data.match(/\w+\.[0-9]/g))];
console.log(res);
Upvotes: 1