Skip to content

Instantly share code, notes, and snippets.

@JoeShep
Created July 6, 2017 20:06
Show Gist options
  • Save JoeShep/6cf6bac5058d1517037954b3ab13abb0 to your computer and use it in GitHub Desktop.
Save JoeShep/6cf6bac5058d1517037954b3ab13abb0 to your computer and use it in GitHub Desktop.
A couple of lodash methods to whet your appetite
// *********** Simple but awesome ***********
console.log("random num", _.random(10, 20));
// *********** Loop it ***********
_.times(5, function(i) {
console.log("adding", i + 2);
});
let testArr = ["wow", "neat", "cool"];
let myArr = _.times(testArr.length, function(i) {
return testArr[i].toUpperCase() + "!"
});
console.log("myArr", myArr );
// *********** Map it ***********
// Fetch the name of the first pet from each owner
let ownerArr = [
{
"owner": "Colin",
"pets": [{"name":"dog1"}, {"name": "dog2"}]
},
{
"owner": "John",
"pets": [{"name":"dog3"}, {"name": "dog4"}]
}
];
// regular JS way
// ownerArr.map(function(owner) {
// return owner.pets[0].name;
// })
_.map(ownerArr, 'pets[0].name');
// *********** Random element from array ***********
let luckyDraw = ["Colin", "Mary", "Fred", "Emerson", "Joan"];
// // let index = Math.floor(Math.random() * (luckyDraw.length))
// console.log(luckyDraw[index])
// console.log(_.sample(luckyDraw));
let posts = [
{ id: "1abc", title: "First blog post", content: "I love to post" },
{ id: "2abc", title: "Second blog post", content: "Here's my opinion" },
// more blog posts
{ id: "34abc", title: "The blog post we want", content: "lodash is awesome" }
// even more blog posts
];
// using JS filter
// let post = posts.filter(function(item) {
// return item.id === "34abc"
// });
// console.log("post", post[0].content );
posts = _.keyBy(posts, "id");
console.log(posts["34abc"].content);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment