Iterating a Specific Number of Times
JavaScript's for loop is standard for iteration, but Lodash's _.times offers a concise alternative for fixed counts.
// Native JavaScript
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Lodash
_.times(5, (index) => {
console.log(index);
});
Accessing Nested Porperties
Lodash's _.map allows using a string path to extract deeply nested values, simplifying code compared to manual traversal.
const owners = [
{ owner: 'Alice', pets: [{ name: 'cat1' }, { name: 'cat2' }] },
{ owner: 'Bob', pets: [{ name: 'dog1' }, { name: 'dog2' }] }
];
// Native JavaScript
const nativeResult = owners.map(owner => owner.pets[0].name);
console.log(nativeResult);
// Lodash
const lodashResult = _.map(owners, 'pets[0].name');
console.log(lodashResult);
Deep Cloning Objects
Deep cloning in JavaScript can be complex; Lodash's _.cloneDeep provides a reliable method, unlike JSON.parse(JSON.stringify()) which fails with functions.
const original = { name: 'Charlie', details: { age: 30 } };
const cloned = _.cloneDeep(original);
console.log(original === cloned); // false
Generating Random Numbers
Lodash's _.random is more flexible than native methods, supporting floating-point results and single-argument use.
// Native JavaScript
function getRandomInRange(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
console.log(getRandomInRange(10, 15));
// Lodash
console.log(_.random(10, 15));
console.log(_.random(10, 15, true)); // floating-point
Merging Objects
_.assign merges properties from multiple source objects into a target object, similar to object spread but with consistent behavior.
const target = { a: 1, b: 2 };
const source = { b: 3, c: 4 };
const merged = _.assign(target, source);
console.log(merged); // { a: 1, b: 3, c: 4 }
Selecting Random Elements
_.sample picks a random element from an array, and _.sampleSize returns multiple random elements.
const items = ['apple', 'banana', 'cherry'];
console.log(_.sample(items));
console.log(_.sampleSize(items, 2));
Checking for Inclusion
_.includes searches for a value in arrays or objects, with a optional starting index.
const array = [1, 2, 3];
const object = { x: 10, y: 20 };
console.log(_.includes(array, 2)); // true
console.log(_.includes(object, 10)); // true
console.log(_.includes(array, 2, 2)); // false
Iterating Over Collections
_.forEach iterates over arrays or objects, providing value and key/index.
_.forEach([10, 20], (value, index) => {
console.log(index, value);
});
_.forEach({ a: 1, b: 2 }, (value, key) => {
console.log(key, value);
});
Transforming Collections with Map
_.map applies a function to each element, supporting arrays, objects, and property shorthand.
const double = n => n * 2;
console.log(_.map([2, 4], double)); // [4, 8]
const users = [{ name: 'Dave' }, { name: 'Eve' }];
console.log(_.map(users, 'name')); // ['Dave', 'Eve']
Checking for Empty Values
_.isEmpty returns true for null, booleans, numbers, empty arrays, or empty objects.
console.log(_.isEmpty(null)); // true
console.log(_.isEmpty([])); // true
console.log(_.isEmpty({})); // true
console.log(_.isEmpty([1, 2])); // false
Removing Duplicates from Arrays
_.uniq creates a duplicate-free version of a array, more concise than manual filtering.
const numbers = [1, 2, 2, 3];
console.log(_.uniq(numbers)); // [1, 2, 3]
Extracting Elements by Index
_.pullAt removes elements at specified indices, returning them in a new array.
const data = [5, 10, 15, 20];
const extracted = _.pullAt(data, 1, 3);
console.log(data); // [5, 15]
console.log(extracted); // [10, 20]
Taking Elements from the End
_.takeRight returns the last n elements of an array.
const sequence = [1, 2, 3, 4];
const lastTwo = _.takeRight(sequence, 2);
console.log(lastTwo); // [3, 4]
Creating Objects from Arrays
_.zipObject pairs keys and values into an object.
const keys = ['x', 'y'];
const values = [100, 200];
console.log(_.zipObject(keys, values)); // { x: 100, y: 200 }
_.zipObjectDeep supports deep property paths for nested structures.
const paths = ['a.b[0].c', 'a.b[1].d'];
const vals = [1, 2];
console.log(_.zipObjectDeep(paths, vals)); // { a: { b: [{ c: 1 }, { d: 2 }] } }
Finding Symmetric Difference
_.xor returns values present in only one of the given arrays.
const set1 = [2, 1];
const set2 = [2, 3];
console.log(_.xor(set1, set2)); // [1, 3]