Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.