Search code examples
javascriptuniqueimacros

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.


Solution

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