0

I have this ajax function returns data as in plain text form.

        $.ajax({
            type: 'GET',
            url: "/addObstacles",
            cache: false,   
            datatype: "text/plain",
            success: function (data) {
                var obstacles = data.split('\n');
                for(var i = 0;i < obstacles.length;i++){
                    if(!obstacles[i] == ''){
                        console.log(obstacles[i]);
                    }
                }
            }
        });

console.log(obstacles[i]):

[[90, 90], [90, 112], [100, 112], [100, 100], [200, 100], [200, 125], [240, 125], [240, 121]]

I want to get rid of all square brackets and the commas after every element and it should look like this:

90,90 90,112 100,112 100,100 200,100 200,125 240,125 240,121 

As this data will be the points for drawing a SVG polyline dynamically. I tried many regex and strip() but no luck.

3
  • obstacles[i].replace(/(\[.*?\])/g, ''); ,obstacles[i].replace(/ *\[[^\]]*]/g, ''); I tried these. Commented May 12, 2020 at 12:23
  • Use brute force: .replace(/\[|\],|\]/g, ''). Commented May 12, 2020 at 12:28
  • Great.. Works fine. Commented May 12, 2020 at 12:30

1 Answer 1

3

Try with Array#flat method

const arr = [[90, 90], [90, 112], [100, 112], [100, 100], [200, 100], [200, 125], [240, 125], [240, 121]];

const res = arr.flat();


//for your desire result
let start = res.shift();
let end   = res.pop();
let center= res.reduce((acc,b,i)=>{
   let l = i+1;
   if(l%2 == 0){
    acc.push(`${res[i-1]} ${b}`)
   }
   return acc
},[])


console.log(start+','+center.join(',')+','+end)

Sign up to request clarification or add additional context in comments.

3 Comments

This throws an error arr.flat is not a function . obstacles[i] is not an array it's just a text returned by python after reading a text file.
@Shyam3089 .is that text file but all in above same format [[n,n]...] like this. Better try with JSON.parse(obstacles[i]).falt(). if still not working please post obstacles
@Prasanth Thanks. Now above code give this: Array(16) [ 90, 90, 90, 112, 100, 112, 100, 100, 200, 100, … ] May be I can remove commas after every 2 elements to get desired structure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.