Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kamauwashington/613a2c4ffae1bf84f108cf12ee9c6d65 to your computer and use it in GitHub Desktop.
Save kamauwashington/613a2c4ffae1bf84f108cf12ee9c6d65 to your computer and use it in GitHub Desktop.

TypeScript Bits

Use provided array functions instead of Lodash

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 the hassle of working with arrays, numbers, objects, strings, etc. However, it is often seen that one of it's 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!

it is so awesome that someone thought about this beforehand!

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 prior to 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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment