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";
John Weisz
  • 30,137
  • 13
  • 89
  • 132
mangesh
  • 355
  • 4
  • 13
  • Take a look at this: https://stackoverflow.com/a/16747921/5309449 – Venomy Nov 10 '17 at 11:13
  • Does this answer your question? [Get all unique values in a JavaScript array (remove duplicates)](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates) – Michael Freidgeim May 08 '20 at 13:42

2 Answers2

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);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • I have this error: "TypeError: (intermediate value).slice is not a function at tutocefano.js:7:29" with your answer? Maybe it's JsBin? – mickaelw Nov 10 '17 at 11:19
  • Yes I know it’s very strange... I just copy/past your code in jsbin and console log of test – mickaelw Nov 10 '17 at 11:21
  • check the demo above – Sajeetharan Nov 10 '17 at 11:21
  • @mickaelw -- See the [code](https://www.typescriptlang.org/play/#src=var%20input%20%3D%20%5B2%2C5%2C2%2C3%2C3%5D%3B%0D%0Avar%20test%20%3D%20%5B%20...new%20Set(input)%20%5D.join()%3B%0D%0Aconsole.log(test)%3B) 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. – John Weisz Nov 10 '17 at 11:27
  • Also, this answer will be giving a compile error on targets below ES6. – John Weisz Nov 10 '17 at 11:28
  • @Sajeetharan If you need ES5 and below, just use `Array.from(new Set(input).values())` instead of the `Set` directly. – John Weisz Nov 10 '17 at 11:31
  • Uhm I think my browser doesn't support Set directly. With Array.from that's work well – mickaelw Nov 10 '17 at 12:10
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"
mickaelw
  • 1,453
  • 2
  • 11
  • 28