Lodash Library usage in Javascript/typescript

Sanjana Human In Tech
2 min readNov 26, 2023

Lodash is a popular utility library for JavaScript that provides a wide range of helpful functions to make working with arrays, objects, strings, and other data types more convenient and efficient. Below are some common Lodash functions along with examples of their usage in both JavaScript and TypeScript:

Installation

First, install Lodash in your project:

npm install lodash

Common Lodash Functions

1. _.map

JavaScript:

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // [1, 4, 9, 16, 25]

TypeScript (with Lodash):

import _ from 'lodash';

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = _.map(numbers, num => num * num);
console.log(squaredNumbers); // [1, 4, 9, 16, 25]

2. _.filter

JavaScript:

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]

TypeScript (with Lodash):

import _ from 'lodash';

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = _.filter(numbers, num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]

3. _.reduce

JavaScript:

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15

TypeScript (with Lodash):

import _ from 'lodash';

const numbers = [1, 2, 3, 4, 5];
const sum = _.reduce(numbers, (acc, num) => acc + num, 0);
console.log(sum); // 15

4. _.groupBy

JavaScript:

const fruits = ['apple', 'banana', 'orange', 'grape', 'apple'];
const groupedByFruit = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
console.log(groupedByFruit); // { apple: 2, banana: 1, orange: 1, grape: 1 }

TypeScript (with Lodash):

import _ from 'lodash';

const fruits = ['apple', 'banana', 'orange', 'grape', 'apple'];
const groupedByFruit = _.groupBy(fruits);
console.log(groupedByFruit); // { apple: 2, banana: 1, orange: 1, grape: 1 }

Thank you for reading this article! Don’t forget to clap only if you think I deserve it👏 and buy me a coffee.

If you have any queries related to ReactNative, I’m always happy to help you. You can reach me on LinkedIn and Gmail.

Happy Learning🚀 Happy Coding💻.

--

--

Sanjana Human In Tech

A React Native front-end enthusiast and dedicated development engineer, eager to expand knowledge on development techniques and collaborate with others.