combine special characters to previous index in array

Viewed 88

Please help javascript masters. I have an array:

["G", "A", ".", ".", ".", ".", ".", ".", "E²", "…", ".", "~", "C²", "D²", "~", "C²", "."]

and the output should be

["G", "A......", "E²….~, "C²", "D²~", "C²."]

All Dot(.), hellip(…) and tilde(~) should stick with the previous index of an array.

My current code for now is this. I don't know what to do next because I'm not familiar all the built in functions in javascript.

var newArr = ["G", "A", ".", ".", ".", ".", ".", ".", "E²", "…", ".", "~", "C²", "D²", "~", "C²", "."];

for(var i=0; i<newArr.length; i++)
  {
    if(/[\&nbsp;\&hellip;\~\.\…\*\_\/]/g.test(newArr[i]))
    {
      // delete this index and transfer current value to previous index
    }
  }
  console.log(newArr);
4 Answers

This should work:

var str = ["G", "A", ".", ".", ".", ".", ".", ".", "E²", "…", ".", "~", "C²", "D²", "~", "C²", "."];

var newStr = str.join('').match(/([\w][^\w]*)/ig);
console.log(newStr);

You could reduce the array and add the wanted parts to the predecessor.

const 
    data = ["G", "A", ".", ".", ".", ".", ".", ".", "E²", "…", ".", "~", "C²", "D²", "~", "C²", "."],
    result = data.reduce((r, s) => {
        if (/^[\.²…~]$/.test(s)) r[r.length - 1] += s;
        else r.push(s);
        return r;
    }, []);

console.log(result);

if i correctly understand what do you want , you can do it like that :) :

    var newArr = ["G", "A", ".", ".", ".", ".", ".", ".", "E²", "…", ".", "~", "C²", "D²", "~", "C²", "."];
    var detect = [".","~", "…"]
    var tab  = [];
    for(var i=0; i<newArr.length; i++)
    {
        var find = 0 ;
        for (var j = 0 ; j < detect.length ; j ++){
            if(newArr[i] == detect[j]){
                find++;
            }
        }
        if(find > 0){
            tab[tab.length - 1] =tab[tab.length - 1] + newArr[i];
        }else{

            tab.push(newArr[i]);
        }
    }
    console.log(newArr);
    console.log(tab);

Perhaps just .join() and .split() is sufficient.

var ss = ["G", "A", ".", ".", ".", ".", ".", ".", "E²", "…", ".", "~", "C²", "D²", "~", "C²", "."],
    rs = ss.join("").split(/(?=\w)/);

console.log(rs);

Related