Unique array comprehension

谁都会走 提交于 2020-01-03 05:43:05

问题


I have the following array in CoffeeScript:

electric_mayhem = [ { name: "Doctor Teeth", instrument: "piano" },
                { name: "Janice", instrument: "piano" },
                { name: "Sgt. Floyd Pepper", instrument: "bass" },
                { name: "Zoot", instrument: "sax" },
                { name: "Lips", instrument: "bass" },
                { name: "Animal", instrument: "drums" } ]

My goal is to get all instrument names from this array.

Expected result: ['piano', 'bass', 'sax', 'drums']

My first solution based on this:

names = (muppet.instrument for muppet in electric_mayhem)
output = {}
output[name] = name for name in names
names = (value for key, value of output)

This is rather long. I looket at the transpiled javascript, and saw the first line is translated to:

names = (function() {
  var _i, _len, _results;
  _results = [];
  for (_i = 0, _len = electric_mayhem.length; _i < _len; _i++) {
    muppet = electric_mayhem[_i];
    _results.push(muppet.instrument);
  }
  return _results;
})();

So I made up a super-hacky solution that uses the _results variable introduced during transpilation:

names = (muppet.instrument for muppet in electric_mayhem \
  when muppet.instrument not in _results)

It works, but I don't like it relies on not documented variable name so it may break with future releases of CoffeeScript.

Is there any one-liner to achieve "unique comprehension" in a non-hacky way?


回答1:


This one-liner will probably do the trick:

names = (key for key of (new -> @[o.instrument] = '' for o in electric_mayhem; @))
//                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//                                 "object comprehension"

As yourself, I (ab)used an associative array to use its keys as the set of unique values.

But, the real trick here is the use of an "object comprehension" to build that array. Or at least, its closest equivalent form currently available on CoffeeScript:

    (new -> @[o.instrument] = '' for o in electric_mayhem; @)
//   ^^^  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  ^  
//  create                 with                            |
//  a new                  that                            |
//  empty                anonymous                         |
//  object               constructor                       |
//                                           don't forget -/
//                                           to return the
//                                        newly created object


来源:https://stackoverflow.com/questions/25260425/unique-array-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!