vcsjones
vcsjones

Reputation: 141668

Creating two arrays from list comprehension

Right now, I am doing this in CoffeeScript:

keys = (key for key of data)
values = (v for k,v of data)

Where data is an an object (not an array). I am trying to create two arrays, where keys is an array of the property names and values is an array of the values.

This compiles to:

var keys, values;
keys = (function() {
    var _results;
    _results = [];
    for (key in data) {
      _results.push(key);
    }
    return _results;
  })();
  values = (function() {
    var _results;
    _results = [];
    for (k in data) {
      v = data[k];
      _results.push(v);
    }
    return _results;
  })();

I'd like to be able to combine these two loops into a single loop, and can't figure out how (or if it's possible) to do this using a list comprehension.

A different attempt I made was to create two arrays and push the items to them myself:

keys = []
values = []
keys.push k for k,v of data

This lets me push the key just fine, but I can't figure out the syntax to push to values as well.

How can I create two arrays from a single list comprehension? Am I better off writing the loop myself?

Upvotes: 3

Views: 654

Answers (2)

epidemian
epidemian

Reputation: 19229

@Jimmy's answer is probably the simplest if you are not using external libraries, but if by any chance you are already using Underscore, you can generate an array of [key, value] arrays and then zip them together:

[keys, values] = _.zip ([k, v] for k, v of data)...

The usage of splats is the same as doing _.zip.apply(_, [k, v] for k, v of data).

Upvotes: 1

Jimmy Bosse
Jimmy Bosse

Reputation: 1404

I think the simplest would be to loop yourself:

keys = []
values = []
for key, value of data
   keys.push key
   values.push value

which transpiles as

var key, keys, value, values;

keys = [];

values = [];

for (key in data) {
  value = data[key];
  keys.push(key);
  values.push(value);
}

Upvotes: 2

Related Questions