Skip to content

Instantly share code, notes, and snippets.

@neoadventist
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neoadventist/a1073993c20729538461 to your computer and use it in GitHub Desktop.
Save neoadventist/a1073993c20729538461 to your computer and use it in GitHub Desktop.
Turning an array to a special kind of object.
//jtri: ok, can't quite wrap my head around this one: how do I turn [ [ 'mike', 'ryan' ], [ 'mike', 'jared' ], [ 'mike', 'jared' ] ] into {"mike": ["ryan", "jared", "jared"], "jared:["mike", "mike"], "ryan":["mike"]} ?
//from falafel
// Helpers
var inArray = function(x) {
return function(xs) {
return xs.indexOf(x) > -1
}
}
var notEq = function(x) {
return function(y) {
return x !== y
}
}
var flatten = function(xs) {
return xs.reduce(function(acc, x) {
return acc.concat(x)
}, [])
}
var unique = function(xs) {
return xs.filter(function(x, i) {
return xs.indexOf(x) == i
})
}
var union = function(xs, ys) {
return unique(flatten(xs.concat(ys)))
}
// Example
var xss = [ [ 'mike', 'ryan' ], [ 'mike', 'jared' ], [ 'mike', 'jared' ] ]
var res = union.apply(null, xss)
.reduce(function(acc, item) {
acc[item] = flatten(xss.filter(inArray(item))).filter(notEq(item))
return acc
}, {})
console.log(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment