Ryan Oliver
Ryan Oliver

Reputation: 87

Scan for duplicate values in a string and remove them

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

Answers (7)

Emircan Ok
Emircan Ok

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

Maheer Ali
Maheer Ali

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

Clyde Lobo
Clyde Lobo

Reputation: 9174

let str = "Z80.8, Z70.0, Z80.8";
let uniq = [...new Set(str.split(", "))].join(", ");

Upvotes: 0

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.

Upvotes: 4

oma
oma

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

Leo
Leo

Reputation: 751

Try this:

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

Upvotes: 0

kockburn
kockburn

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

Related Questions