0

For example, I have object:

o = {a: 1, b: 2, c: 3}

and I need to write function that returns 2d array:

arr = [['a', 'b', 'c'], [1, 2, 3]];

For now I have function that creates simple array, but I don't know how to go from there (knowledge not found). The function:

function keysAndValues(o){
  var arr= []; 
  for(key in data)
  {   
      arr.push(key);
      //or
      arr.push(data[key]);

  }
  return arr;
};

How can I create 2d array?

EDIT

All the answers are correct, and I have learned couple of new things. Thank you a lot guys. Bad thing is only one can get green arrow, so it will go to the first one who gave answer.

5 Answers 5

2

I will go the library approach since everyone wrote their take on the subject, using underscore's _.keys and _.values

_.keys(o);

will return o keys, while

_.values(o)

will return o values. So from here you could do

arr = [_.keys(o), _.values(o)]
Sign up to request clarification or add additional context in comments.

Comments

2

There needs to be three arrays, an outer array that contains two arrays at indexes 0 and 1. Then just push to the appropriate array:

function keysAndValues(data){
  var arr= [[],[]]; //array containing two arrays
  for(key in data)
  {   
      arr[0].push(key);
      arr[1].push(data[key]);
  }
  return arr;
};

JS Fiddle: http://jsfiddle.net/g2Udf/

Comments

2

You can make arr an array containing initially 2 empty arrays, then push the elements into those arrays.

function keysAndValues(data) {
  var arr = [[], []];
  for (key in data) {
    if (data.hasOwnProperty(key)) {
      arr[0].push(key);
      arr[1].push(data[key]);
    }
  }
  return arr;
}

Comments

1
function keysAndValues(o){
var arr = new Array([] ,[]); 
for(key in o)
  {   
    arr[0].push(key);
    arr[1].push(o[key]);

  }
return arr;
};

You basically want an array containing two arrays: 0: all keys 1: all values

So push all keys into arr[0] and all values into arr[1]

Comments

1

You can use a for in loop to iterate over your object, add the keys and values to individual arrays, and return an array containing both of these generated arrays:

var o = {a: 1, b: 2, c: 3}

function keyValueArray (o) {
  var keys = [];
  var values = [];

  for (var k in o ) {
    keys.push(k);
    values.push(o[k]);
  }
  return [keys,values]
}

keyValueArray(o);

jsfiddle

Comments

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.