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.

3

7 Answers 7

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.
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

I'm sorry. Thank you.
0

Try this:

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

Comments

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.