Skip to content

Instantly share code, notes, and snippets.

@lsongdev
Created March 3, 2015 09:57
Show Gist options
  • Select an option

  • Save lsongdev/d94e4cb7b26c95ef9646 to your computer and use it in GitHub Desktop.

Select an option

Save lsongdev/d94e4cb7b26c95ef9646 to your computer and use it in GitHub Desktop.
/**
* sort method
*/
String.prototype.sort = function(){
return this
.split('')
.sort()
.join('');
};
/**
* return an array of a give object's values .
*/
Object.values = function(obj){
var results = [];
for(key in obj){
results.push( obj[ key ] );
}
return results;
};
var fn = function(arr){
var group = {};
arr.forEach(function(item){
var key = item.sort();
group[ key ] = group[ key ] || [ ];
group[ key ].push(item);
});
return Object.values(group);
};
// [
// "cars",
// "thing",
// "scar",
// "dog",
// "god",
// "arcs",
// "the"
// ]
console.log(fn("cars scar arcs thing the dog god".split(' ')));
// ➜ ~ node Desktop/javascript.js
// [ [ 'cars', 'scar', 'arcs' ],
// [ 'thing' ],
// [ 'dog', 'god' ],
// [ 'the' ] ]
#!/usr/bin/env ruby
p %w"cars scar arcs thing the dog god".group_by { |item|
item.chars.sort
}.values
# ➜ ~ ruby Desktop/ruby.rb
# [["cars", "scar", "arcs"], ["thing"], ["the"], ["dog", "god"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment