Lodash Multidimensional Pluck
With the lodash library, I'd like to be able to pluck multiple values into a multi-dimensional array, along the lines of: var arr = [{ a: 2, b: 3, c: 4 }, { a: 1, b: 4, c: 2 }]; _.
Solution 1:
There is no pluck on multiple keys, but you can do this:
_.map(['a', 'c'], function(path) {
return _.pluck(arr, path);
});
This will return values grouped by key.
Edit:
_.mpluck = function(collection, paths) {
return _.zip(
_.map(paths, function(path) {
return _.pluck(collection, path);
})
);
}
var arr = [{ a: 2, b: 3, c: 4 }, { a: 1, b: 4, c: 2 }];
_.mpluck(arr, ['a', 'c']) --> [[2, 4], [1, 2]]
this will replace each object by an array of the specified keys.
Without lodash:
functionmpluck(collection, paths) {
return collection.map(function(obj) {
return paths.map(function(path) {
return obj[path];
});
});
}
Solution 2:
Solution without lodash:
functionpluck(arr, k) {
return arr.reduce(function (r, a) {
r.push(k.reduce(function (rr, aa) {
rr.push(a[aa]);
return rr;
}, []));
return r;
}, []);
}
var arr = [{ a: 2, b: 3, c: 4 }, { a: 1, b: 4, c: 2 }],
x = pluck(arr, ['a', 'c']);
document.write('<pre>' + JSON.stringify(x, 0, 4) + '</pre>');
Post a Comment for "Lodash Multidimensional Pluck"