JS Array Functions Instead of Lodash

TypeScript Bits

TypeScript Bits are small, easily digestible pieces of information to encourage TypeScript/JavaScript best practices. From beginner to intermediate, to ninja, these bits are for you 😄


Estimated reading time : 2 minutes

Lodash is an amazing library and is often used to minimize the hassle of working with arrays, numbers, objects, strings, etc. However, it is often seen that one of its primary uses is array manipulation, and accessing elements within.

TypeScript (and ES6) have the majority this functionality built in!

The example below illustrates the find method in Lodash vs TS/JS :

Before

import * as _ from 'lodash';
const workingArray : Array<number> = [0,1,2,3,4,5,6,7,8,9];
const foundResult : number = _.find(workingArray,(item : number) => item > 8);
console.log(foundResult); // prints 9

After

const workingArray : Array<number> = [0,1,2,3,4,5,6,7,8,9];
const foundResult : number | undefined = workingArray.find((item : number) => item > 8);
console.log(foundResult); // prints 9

But wait! I may need an index as well as the individual item!

const workingArray : Array<number> = [0,1,2,3,4,5,6,7,8,9];
const foundResult : number | undefined = workingArray.find((item : number, index : number) => index > 8 || item > 8);
console.log(foundResult); // prints 9

Notes

  • Lodash comes at a cost in file size and performance (in many cases compared to native), consider existing functionality before importing Lodash
  • IMPORTANT While inline anonymous functions work in most cases for simple logic, opt for a separate named function (imported from a separate file if warranted) to house complex manipulation/accessor logic promoting reuse and independent testability.
  • The above is a simple example using find, there are more methods available :
    • every, some, includes, filter, map, reduce, and more!

Visit the Array Prototype Documentation for more in-depth information!