Andre_k
Andre_k

Reputation: 1730

Get unique string in imacros Javascript

Suppose I have a string "1,2,1,2,2,3,4", now I want to get unique from this such that My output looks like 1,2,3,4 I have tried with

TAG POS=1 TYPE=div ATTR=class:type-txt<sp>icon-txt&&TXT:* EXTRACT=TXT
SET ag EVAL("'{{!EXTRACT}}'.split('BHK')[0].replace(/(.)\1+/g, '$1');")
PROMPT {{ag}}

This is the link of website from where I extract data

The o\p of "ag" is 1,1,2,1,1,2,3

Is there any way by which it could be solved.

Thanks.

Upvotes: 0

Views: 121

Answers (3)

D-Money
D-Money

Reputation: 2465

Using ES6 you can take advantage of the spread operator:

var myString = "1,2,1,2,2,3,4";
var output = [... new Set(myString)] // [1,2,3,4]

If you want the output to be a string:

output.join(); // "1,2,3,4"

Upvotes: 0

marvel308
marvel308

Reputation: 10458

You can do

let str =  "1,2,1,2,2,3,4";

let result = Object.keys(str.split(',').reduce((a, b) => (a[b] = true, a), {}));

console.log(result);

Explanation, I used the fact that the keys of an object would be unique, so after splitting the string, I just created an object with those elements as properties, the keys would all be unique.

You can also try

let str = "1,2,1,2,2,3,4";

let result = Array.from(new Set(str.split(',')));

console.log(result);

Upvotes: 2

Rajesh
Rajesh

Reputation: 24925

You can try something like this:

Logic:

  • Split string using delimiter(,) to get array of values.
  • Loop over this array.
  • Concat string to an empty string to create your final string.
  • Check if the value exists in your final string.
    • If yes, do not concat.
    • If no, concat it.
  • Return this final string.

For ease in manipulation, I have added ,<value> and then displayed string from 1 index,

let str =  "1,2,1,2,2,3,4";

let result = str.split(',').reduce(function(p, c){
  if(p.indexOf(c) < 0) {
    p += ',' + c
  }
  return p;
}, '');

console.log(result.substring(1));

Upvotes: 1

Related Questions