1

Here i am facing a problem as when getting response from rails controller as json object as:

"77.576343,12.964343,77.576413,12.963679,77.575233,12.96545,77.5760913,12.9657723,77.575217,12.965333"

But i need to use this data as array for a success function in ajax as

[["77.570934", "12.964462"], ["77.57199", "12.96455"], ["77.571046", "12.964471"], ["77.572142", "12.964577"]]

How can i convert it there in ajax success function. Please help me. Thanx in advance.

1
  • It's unclear whether you are consuming somebody else's service, or whether you're trying to pass data from your own back end to your front end. If you own both sides, you should just fix the format of the JSON your Rails server is outputting. Commented Jun 15, 2016 at 17:44

2 Answers 2

2

You could split the string and build a new array with Array#reduce.

var string = "77.576343,12.964343,77.576413,12.963679,77.575233,12.96545,77.5760913,12.9657723,77.575217,12.965333",
    array = string.split(',').reduce(function (r, a, i) {
        if (!(i % 2)) r.push([]);
        r[r.length - 1].push(a);
        return r;
    }, []);
	
console.log(array);

Or without reduce, but with Array#forEach.

var string = "77.576343,12.964343,77.576413,12.963679,77.575233,12.96545,77.5760913,12.9657723,77.575217,12.965333",
    array = [];

string.split(',').forEach(function (a, i) {
    i % 2 || array.push([]);
    array[array.length - 1].push(a);
});
	
console.log(array);

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

3 Comments

I had this exact answer (well with different variable names) ready to add.
I recommend turning the inline || back into a formal if(). It is a more advanced concept (imho) that is probably not self evident to someone who is starting out.
Thanx for replying but i fixed my problem by using JSON.stringify() method. Tnanx again for your valuable answer.
0

My friend "77.576343,12.964343,77.576413,12.963679,77.575233,12.96545,77.5760913,12.9657723,77.575217,12.965333" is string. Try with a javascript function split.

var x = "77.576343,12.964343,77.576413,12.963679,77.575233,12.96545,77.5760913,12.9657723,77.575217,12.965333";
var array = x.split(',');

array should be an Array with 10 positions. make an simple loop like:

var newArray = [];
var tmpArray = [];
for(var i = 0; i < array.length; i++){
tmpArray.push(array[i]);
  if((i+1) % 2 === 0){
    newArray.push(tmpArray);
    tmpArray = [];
  }
}

1 Comment

Thanx for your valuable answer @Julian Porras

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.