Home > Net >  JS arrays: merging together following items that starts by the same char (refer to the next loop in
JS arrays: merging together following items that starts by the same char (refer to the next loop in

Time:12-04

Basically I have an item with HTML tags in it, the problem is that I have some instructions starting by an @ in this array too. Here's what the array looks like:

store = ["@if str == 'hello'", "<div>", "<h1>hello world</h1>", "</div>", "@else", "<p>Hello</p>"]

I want to group every HTML tags between the instruction items into one array item, resulted like this:

store = ["@if str == 'hello'", "<div><h1>hello world</h1></div>", "@else", "<p>Hello</p>"]

So I ended up with this code:

const store = ["@if str == 'hello'", "<div>", "<h1>hello world</h1>", "</div>", "@else", "<p>Hello</p>"]
const merged = [];

for (let i = 0; i < store.length; i  ) {
    if(store[i].slice(0, 1) == "@"){
        merged.push(store[i]);
    } else if (store[i].slice(0, 1) == "<") {
        while (store[i 1] == "<") {
            str = store[i]   store[i 1];
            merged.push(str)
        }
    }
}
console.log(merged);

But it's working, I guess because of the "[i 1]" that I use on the store array.

CodePudding user response:

Have another variable store the accumulating element string, then push it when you it another condition.

const store = ["@if str == 'hello'", "<div>", "<h1>hello world</h1>", "</div>", "@else", "<p>Hello</p>"]
const merged = [];
let current = [];

for (let i = 0; i < store.length; i  ) {
    if(store[i].slice(0, 1) == "@"){
        if(current.length) merged.push(current.join(''))
        current = []
        merged.push(store[i]);
    } else if (store[i].slice(0, 1) == "<") {
       current.push(store[i])
    }
}
console.log(merged);

  • Related