Skip to content

Instantly share code, notes, and snippets.

@bodokaiser
Last active August 29, 2015 14:02
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 bodokaiser/5f958f6b968367f6a0e5 to your computer and use it in GitHub Desktop.
Save bodokaiser/5f958f6b968367f6a0e5 to your computer and use it in GitHub Desktop.
Ultimate string parsing map reduce action.
var string = 'colors:red, colors:blue, sizes:42, sizes:44';
var obj = string.split(', ')
.map(function(entry) {
return entry.split(':').reduce(function(prev, curr) {
if (!prev.name) {
prev.name = curr;
prev.value = '';
} else {
prev.value += curr;
}
return prev;
}, {});
})
.reduce(function(prev, curr) {
if (!prev.hasOwnProperty(curr.name)) {
prev[curr.name] = [curr.value];
}
if (!~prev[curr.name].indexOf(curr.value)) {
prev[curr.name].push(curr.value);
}
return prev;
}, {});
// { colors: ['red', 'blue'], sizes: [42, 44] }
console.log(obj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment