Finally, an edge runtime that works out-of-the-box with Next.js, Remix, Nuxt, and more. Check it out!

Guides & Tutorials

Common JavaScript functions with Lodash

Guides & Tutorials

Common JavaScript functions with Lodash

There are some things in JavaScript that seem tedious to write. When I first started learning the language a few years back, I found a few common functions like shuffle and range that are included in the Ruby and Python API, but are not available with JavaScript. Luckily there are libraries like Lodash that provides functions for solved problems like shuffling an array while delivering modularity.

Lodash is one of the most popular JavaScript utlitilty libraries with more than 2 billion downloads. It accounts for 4% of npm’s weekly download traffic and it’s directly depended upon by more than 27,000 packages and indirectly depended upon by 100,000 packages (30% of npm packages).

I am going to briefly go over some of my favorite functions in Lodash while approaching some common situations in JavaScript.

shuffle

Take a common task like Shuffling, not the popularize dance from the one-hit-wonders LMFAO, but the practice of randomizing an array of data. This is something I do quite often, which is why it’s nice to have.

// JavaScript

var arr = ["a", "b", "c", "d"];

function shuffle(array) {
 var currentIndex = arr.length, temporaryValue, randomIndex;

 // While there remain elements to shuffle...
 while (0 !== currentIndex) {
   // Pick a remaining element...
   randomIndex = Math.floor(Math.random() * currentIndex);
   currentIndex -= 1;

   // And swap it with the current element.
   temporaryValue = array[currentIndex];
   array[currentIndex] = array[randomIndex];
   array[randomIndex] = temporaryValue;
 }

 return array;
}

shuffle(arr);
// returns a shuffled arr

My example is quite verbose and could definitely be written with less code, but the real issue is the ceremony of rewriting this every-time I want to shuffle in a project. The nice part of Lodash is that it is a library available to insert in your project using normal ES6 imports.

I prefer to use destructuring to include only the Lodash functions I need. My example for doing shuffling in Lodash is a one liner and quite trivial.

// Lodash

  import { shuffle } from "lodash";

  shuffle(arr)
  // returns a shuffled arr

I am to do the same shuffle as above but in only one line of code.

range

A common problem for learning to program is creating a lottery number generator. To start I need an array of all numbers from 1 to 100. In JavaScript, I can write a quick loop to create an array that represents every number 1 to 100 inclusively.

  var numbers = []; create an empty array

  for (var i = 1; i <= 100; i++) {
     numbers.push(i);
  }

  console.log(numbers)
  // [1, 2, 3, ..., 100]

With Lodash the method needed is the range function, which only requires the bounds for the array as arguments. This provides the flexibility to create custom ranges on the fly for any use case.

  import { range } from "lodash";

  var numbers = range(1, 100);

  console.log(numbers)

  // [1, 2, 3, ..., 100]

Using the lodash range has other benefits than just writing less code. I was able to shave .07 miliseconds with the ladder implementation.

I tracked this using the browser’s Performance API

// Call to range loop took 0.030000000000001137 milliseconds.

// Call to lodash range took 0.23000000000000398 milliseconds.

sampleSize

Now if I want to pick a random sample set of the numbers variable for my lottery number picker.

  var getRandomLottoNumbers = function (numbers) {
    while (numbers.length > 5) {
      numbers.splice(Math.floor(Math.random() \* numbers.length), 1);
    }

    return numbers;
  };

Lodash, once again only requires an import of one function to accomplish this.

  import { sampleSize }

  sampleSize(numbers, 5)

Similar to what I saw with range there were performance benefits I saw with the lodash implementation of sampleSize.

I did not discover Lodash until a year into my JavaScript development which is why I am happy to share it everyone who reads this post. I recommend checking out their documentation for other useful functions you can use in your code.

Lodash hosts their documentation with Netlify on the Open Source Plan. If you have an open source project you like as much as I do Lodash, let them know about our open source plan available to them for free.

Keep reading

Recent posts

Book cover with the title Deliver web project 10 times faster with Jamstack enterprise

Deliver web projects 10× faster

Get the whitepaper