2

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.

Ryan Walls
  • 191
  • 1
  • 13
  • Are all the values separated by a comma? – nicholaswmin Feb 05 '19 at 15:11
  • 1
    split by comma than https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates – epascarello Feb 05 '19 at 15:11
  • 1
    Possible duplicate of [Remove occurrences of duplicate words in a string](https://stackoverflow.com/questions/16843991/remove-occurrences-of-duplicate-words-in-a-string) – Nik Feb 05 '19 at 15:14

7 Answers7

4

Use something like:

str
  .split(',')
  .map(function(s) { return s.trim() })
  .filter(function(v, i, a) { return a.indexOf(v) === i })
  .join(', ');
  1. Split will make it an array by splitting the string at every comma.
  2. Map will remove leading and trailing spaces.
  3. Filter will remove any element that is already in the array.
  4. Join will join back the array to one string.
1

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);
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
1

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

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Emircan Ok
  • 320
  • 2
  • 13
0

Try this:

let str = "Z80.8, Z70.0, Z80.8";
str = [...new Set(str.split(", "))].join(", ");
console.log(str);
Leo
  • 741
  • 6
  • 14
0

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);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0
let str = "Z80.8, Z70.0, Z80.8";
let uniq = [...new Set(str.split(", "))].join(", ");
Clyde Lobo
  • 9,126
  • 7
  • 34
  • 61
-1

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

oma
  • 1,804
  • 12
  • 13