Categories
Lodash

Learning JavaScript by Implementing Lodash Methods — Arrays and Objects

Spread the love

Lodash is a very useful utility library that lets us work with objects and arrays easily.

However, now that the JavaScript standard library is catching up to libraries such as Lodash, we can implement many of the functions in simple ways.

In this article, we’ll look at Lodash methods for zipping arrays into object properties and values, and looping through arrays and objects.

zipObject

The Lodash zipObject method props 2 arrays into object properties and values. The first array has the property names and the second has the property values.

We can implement our own zipObject method as follows:

const zipObject = (props, vals) => {
  let obj = {};
  for (let i = 0; i < props.length; i++) {
    obj[props[i]] = vals[i];
  }
  return obj;
}

In the code above, we create an empty object. Then we loop through the props array to get the property names and index.

We then use that to populate the obj object with our own properties and corresponding values by using the index to access the entries in the vals array.

Then when we call it as follows:

const result = zipObject(['a', 'b'], [1, 2]);

We then get the value for result :

{
  "a": 1,
  "b": 2
}

countBy

The countBy method creates an object from an array that composes the array entries as the keys, where the keys are processed through an iteratee function. The value of each key is the count of the keys after they’ve been mapped through iteratee .

The iteratee takes one argument and maps the parameter to somethhing else.

We can implement it as follows:

const countBy = (arr, iteratee) => {
  let obj = {};
  for (const a of arr) {
    if (typeof obj[iteratee(a)] === 'undefined') {
      obj[iteratee(a)] = 0;
    } else {
      obj[iteratee(a)]++;
    }
  }
  return obj;
}

In the code above, we mapped the keys by calling iteratee with the key, which is the array entry.

Then we set the corresponding value to 0 when the property hasn’t been defined yet.

Otherwise, we increment the value by 1. In the end, we returnobj .

Then when we call it as follows:

const result = countBy([6.1, 4.2, 6.3], Math.floor);

We get that result is:

{
  "4": 0,
  "6": 1
}

forEach

The Lodash forEach method loops through an element in a collection and invokes iteratee on each element.

The iteratee function can stop the execution of the loop bu returning false explicitly.

It can take an array or an object as the first argument.

We can implement it as follows:

const forEach = (collection, iteratee) => {
  if (Array.isArray(collection)) {
    for (const a of collection) {
      const result = iteratee(a)
      if (result === false) {
        break;
      }
    }
  } else {
    for (const a of Object.keys(collection)) {
      const result = iteratee(collection[a], a)
      if (result === false) {
        break;
      }
    }
  }
}

In the code above, we first check if the collection is an array. If it is, then we use a for...of loop to loop through each entry and call iteratee on each entry.

If it returns false , then we stop the loop.

Likewise, if the collection isn’t an array, then we loop through the keys of the object by getting the keys with Object.keys and then run iteratee on each key-value pair.

The parameters of iteratee in the object case is the value and then the key, whereas the iteratee in the array case is just the array entry.

If iteratee returns false , then we stop the loop.

Then when we call it as follows:

forEach([1, 2], (value) => {
  if (value === 2) {
    return false;
  }
  console.log(value);
});

forEach({
  'a': 1,
  'b': 2
}, (value, key) => {
  console.log(key);
});

We get that the first forEach logs 1 and the second call logs ‘a’ and ‘b’.

Conclusion

The zipObject method can easily be implemented with the for loop and populating the keys and values into an object and return it.

The countBy method is similar, but the values are the count of each item, which is determined by first calling an iteratee function to populate the keys and count the number of items that appears after calling the iteratee function.

Finally, the forEach function can be implemented with the for...of loop and breaking the loop when the iteratee function returns false.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *