Last active
August 29, 2015 14:07
-
-
Save neoadventist/a1073993c20729538461 to your computer and use it in GitHub Desktop.
Turning an array to a special kind of object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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