[ Regexp ] [Solved] Intermediate Algorithm Scripting: Steamroller

I solved the “problem” in this mode

function steamrollArray(arr) {
let regex = /[\[\]]/g;
let strSteamRoller = JSON.stringify(arr).replace(regex, ""); 
// Remove Empty Array 
strSteamRoller = strSteamRoller.replace(",,", ",");

let arrSteamRoller = JSON.parse("[" + strSteamRoller +"]");


return arrSteamRoller;

}

I work at Intermediate Algorithm Scripting: Steamroller, my question is how to improvement regex on my code for resolve problem with empty array?


function steamrollArray(arr) {

let regex = /[\[\]]/gi;
let strSteamRoller = JSON.stringify(arr).replace(regex, "");  
let arrSteamRoller = JSON.parse("[" + strSteamRoller +"]");

return arrSteamRoller;
}

steamrollArray([1, [], [3, [[4]]]]); // doesn't work

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36.

Challenge: Steamroller

Link to the challenge:

First of all, I’m not sure you need i flag :wink:
Secondly, if you’re using range selector [...] then you need to specify how much character within the range you want to match, for example [\[\]]+ will match from one to unlimited amount of characters.

I am pretty sure that a string-based solution isn’t how this challenge was intended to be answered, but I am tickled at the ingenuity of the solution. You might need to strip out extra commas too.

1 Like

This solution will have a problem with empty arrays, as after removing brackets you will have something like this: "1, , 3, 4" with one unnecessary comma

Secondly, JSON.stringify + regex could very simply be replaced with arr.toString() :slight_smile:

Well an idea is that regexp, but reverse matched

([\d\w,"])|([])|({})

Here page of Intermediate Algorithm Scripting: Steamroller

with toString () object return “object”
with stringify object return {}