Search code examples
javascriptarraysmobile-application

How to take certain parts in one array and convert them into another character in javascript


I have created a code which recognises the colour red as "on" and the colour blue as "off", these on's and off's are then "pushed" into an empty array called initial, this can be seen below.

if (red > blue){
    initial.push("on");
    console.log(initital);
    console.log(initial.length);
    return true;
}

else {
    initial.push("off");
    console.log(initial);
    console.log(initial.length);
    return false;

}

when this is run and output like this is shown:

[on, on, on, off, off, off, on, on, on, off, off, off, on]

But I need to turn these on's and off's into dashes (_) and dots (.) and .push them in another array called senseMake, if that's possible.

The rules are:

  • On for 1–2 time units = Dot
  • On for ≥ 3 time units = Dash

Tried creating a for loop but isn't working, please help.

So the result of the array above should be: [_, ,_, ,.]

The loop that I used was

for (i=0; i<initial.length; i += 2) senseMake.push("."); console.log(senseMake);

for (i=0; i<initial.length; i += 3) senseMake.push("_"); console.log(senseMake);


Solution

  • Here's an efficient solution (no iteration) using regex. The whole thing could be around 2 lines, i.e:

    var initial = ['on', 'on', 'on', 'off', 'off', 'off', 'on', 'on', 'on', 'off', 'on', 'off'];
    var senseMake = initial.join('').replace(/(on){3,}/gi, '_').replace(/(on){1,2}/gi, '.').replace(/off/gi, '').split('');
    

    But I've broken it into multiple lines in the snippet to make it easier to understand.

    var initial = ['on', 'on', 'on', 'off', 'off', 'off', 'on', 'on', 'on', 'off', 'on', 'off'];
    var senseMake = initial.join(''); // join the elements of the array into a string
    senseMake = senseMake.replace(/(on){3,}/gi, '_'); // replace every instance of 3+ 'ons' with a _
    senseMake = senseMake.replace(/(on){1,2}/gi, '.'); // replace every instance of 1-2 'ons' with a .
    senseMake = senseMake.replace(/off/gi, ''); // replace every instance of 'off' with an empty string
    senseMake = senseMake.split(''); // split every character into the elements of an array
    document.write(JSON.stringify(senseMake, null, '  ')); // display result in window
    * { font-family: monospace; }

    Hope this helps!