Skip to content

Lodash

Updated: at 01:00 AM

Lodash

Replace variables inside

const template =
  "Your pet {{pets.name}} has gone outside via {{door.friendlyName}}";
const data = {
  pets: { id: "kdreir10", name: "Kuha" },
  door: {
    friendlyName: "FrontDoor",
  },
};

_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
const interpolated = _.template(template)(data);
console.log(interpolated); // Your pet Kuha has gone outside via FrontDoor

Chain

_.chain(["192.168.0.1", ""]).last().isEmpty().value(); // true
_.chain([1, 2, 3, 4])
  .map(n => n * n)
  .tap(console.log)
  //.thru((n) => n.reverse())
  .value();
const arr = [
    {
        entityId: '240AC41D7001',
        entityType: 'PRODUCT'
    },
    {
        entityId: 'dhye-13si',
        entityType: 'PET'
    },
    {
        entityId: '240AC41D7002',
        entityType: 'PRODUCT'
    }
]

const data: string[] = _.chain(arr)
    .filter((o) => o.entityType === 'PRODUCT')
    .map((o)=> o.entityId)
    .uniq()
    .value(); // ["240AC41D7001", "240AC41D7002"]

MIXIN and CHAIN

const vowels = (array) => _.filter(array, str => /[aeiou]/i.test(str);

_.mixin({vowels});

_.chain(['Cheese','BnB','Hotel', 'TV']).vowels().value(); // ["Cheese", "Hotel"]

Other

// isEmpty
_.isEmpty(null); //true
_.isEmpty({}); //true
_.isEmpty([]); // true
_.isEmpty([1]); // false

// size
_.size([2, 3]); //2
_.size({ a: 1, b: [2, 3], c: {} }); //3

// REMOVE or OMIT
var objA = { name: "colin", car: "suzuki", age: 17 };
objA = _.omit(objA, ["car", "age"]); // equivalent to objA.remove(['car', 'age']);
objA; // {"name": "colin"}

// CHECK IF OBJECT HAS THESE PROPERTIES
const props = ["businessTitle", "email", "firstName", "lastName"];
_.every(props, _.partial(_.has, someObj)); // true | false

let arr = [
  { id: 1, name: "a" },
  { id: 2, name: "b" },
];
// FIND finds 1st match returns Object
_.find(arr, { id: 2 }); //  {id:2,name:"b"}

// FILTER returns ARR
_.filter(arr, { id: 2 }); //  [{id:2,name:"b"}]

_.first(arr); // same as arr[0]
_.last(arr); // returns last item from array
_.takeRight(arr, n); // returns n last item from array

_.drop([abcdef], 2); // → [   cdef ]
_.dropRight([abcdef], 2); // → [ abcd   ]
_.take([abcdef], 2); // → [ ab     ]
_.takeRight([abcdef], 2); // → [     de ]

UNIQ

_.uniqBy([{..},{..}], 'userId'); // userId being an attribute of an item of this array
_.uniqBy([{..},{..}], (i) => [i.userId,i.deviceId].join());

// uniqBy only works for 1 prop
profiles = _.uniqBy(profiles, 'id');

// for multiple prop use the following
profiles = [profile, ...profiles];
profiles = _.uniqBy(profiles, v => [v.id, v.name].join());

GROUPING

_.groupBy([{ code: "RAKE" }, { code: "RAKE" }, { code: "ERROR" }], "code"); //
// {
//    "RAKE":  [{"code":"RAKE"},{"code":"RAKE"}],
//    "ERROR": [{"code":"ERROR"}]
// }

_.countBy([{ code: "RAKE" }, { code: "RAKE" }, { code: "ERROR" }], "code");
// {'RAKE':2, 'ERROR':1}

MAP

const arr = [
  { name: "Virginia", age: 45 },
  { name: "Debra", age: 34 },
  { name: "Jerry", age: 55 },
];

_.map(arr, "name"); // ['Virginia', 'Debra', 'Jerry'];
_.map(arr, i => _.pick(i, ["name"])); // [{ name: 'Virginia'},{ name: 'Debra'},{ name: 'Jerry'}];
_.map(arr, i => _.omit(i, ["name"])); // [{ age: 45 },{ age: 34 },{ age: 55 }];

Difference

if(_.difference(subset, superset).length == 0) // it means subset array is in superset array!!

RANDOM

_.random(15, 20); // random number between 15-20
_.random(20); // random number between 0-20
_.random(15, 20, true); // random floating numbers between 15-20
_.sample(["Colin", "John", "James"]); // John
_.sample(["Colin", "John", "James"], 2); // ['John','James']

TIMES

_.times(5, i => {
  console.log(i); // 0, 1, 2, 3, 4
});

_.throttle, _.debounce

scrollBar.onscroll(_.throttle(onScrollFunc, 400)); // throttle ensures the onScrollFunc is called approximately 400ms in between
submitButton.onclick(
  _.debounce(onSubmitFunc, 400, {
    leading: true,
    trailing: false,
  })
); // debounce ensures the onSubmitFunc is not called multiple times within 400ms

Before

const fp = _.before(2, function () {
  console.log("OMG!");
});

fp();
fp();
fp();
fp();
fp();
fp();
// prints OMG only 1 time;
If you enjoy the content, please consider supporting work