user3767164
user3767164

Reputation: 161

Split a 2D array into single arrays

I am bit new in JQuery ,,I have a 2D Array

2DArray =[2.0,6.31]
         [3.0,6.09]
         [4.0,7.44]

I want to split it into 2 One dimensional Array like this:

[2.0, 3.0, 4.0]    
[6.31, 6.09, 7.44]

I have read posts about convert single array into multidimensional array but not vice versa ...

Any suggestion would be helpful

Upvotes: 1

Views: 5023

Answers (3)

Js.
Js.

Reputation: 423

You could use the JavsScript map() method:

var twoDArray =[[2.0,6.31],
               [3.0,6.09],
               [4.0,7.44]];

var xArray = twoDArray.map(function(tuple) {
    return tuple[0];
});
var yArray = twoDArray.map(function(tuple) {
    return tuple[1];
});

Upvotes: 3

Liam
Liam

Reputation: 29714

This should about do it, you have to loop:

var twoDArray =[[2.0,6.31],
         [3.0,6.09],
         [4.0,7.44]];

var xArray = [];
var yArray = [];

$.each(twoDArray, function(index, value) {
    xArray.push(value[0]);
    yArray.push(value[1]);
});

BTW 2DArray is an invalid variable name. You can't use 2 at the start of a variable.

Also your array declaration is invalid.

Upvotes: 3

Tech
Tech

Reputation: 214

Create 2 arrays for each row put first column in first array and second on in the second array. This link would give you all the array operation you have in jQuery.

http://learn.jquery.com/javascript-101/arrays/

Alternately you can even use a for loop with index.

Hope this helps. Happy coding.

Upvotes: -1

Related Questions