0

In TypeScript I want distinct values from comma separated duplicate string:

this.Proid = this.ProductIdList.map(function (e) { return e.ProductId;}).join(',');
this.Proid = "2,5,2,3,3";

And I need :

this.Proid = "2,5,3";
2

2 Answers 2

6

This can be simply done with with ES6,

var input = [2,5,2,3,3];
var test = [ ...new Set(input) ].join();

DEMO

var input = [2,5,2,3,3];
var test = [ ...new Set(input) ].join();
console.log(test);

EDIT

For ES5 and below, you can try,

var input = [2,5,2,3,3];
var test = Array.from(new Set(input).values()).join();
console.log(test);

Sign up to request clarification or add additional context in comments.

7 Comments

I have this error: "TypeError: (intermediate value).slice is not a function at tutocefano.js:7:29" with your answer? Maybe it's JsBin?
Yes I know it’s very strange... I just copy/past your code in jsbin and console log of test
check the demo above
@mickaelw -- See the code that the array destructuring statement [ ...set ] is compiled to, for ES5 target and below it will use slice to do the shallow array copy. The browser in question simply doesn't support it, and needs a polyfill.
Also, this answer will be giving a compile error on targets below ES6.
|
5

One possible solution:

this.ProductIdList = ["2","5","2","3","3"]
const tab = this.ProductIdList.reduce((acc, value) => {
    return !acc.includes(value) ? acc.concat(value) : acc
}, []).join(',');

console.log(tab) //"2,5,3"

You can do in one line too:

this.ProductIdList = ["2","5","2","3","3"]
const tab = this.ProductIdList.reduce((acc, value) => !acc.includes(value) ? acc.concat(value) : acc, []).join(',');

console.log(tab) //"2,5,3"

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.