Categories
JavaScript

Lodash Methods That Can Be Easily Implemented in Plain JavaScript

Lodash is a utility library that has lots of methods for manipulating objects. It has stuff that we use all the time and also things that we don’t use frequently or don’t think of using.

We can implement many Lodash methods with plain JavaScript. In this article, we’ll look at some array methods that can be implemented in plain JavaScript.

chunk

In Lodash, the chunk method splits an array into groups by size. We can implement it as follows with plain JavaScript:

const chunk = (arr, size) => {
  const chunkedArr = [];
  for (let i = 0; i < arr.length; i += size) {
    chunkedArr.push(arr.slice(i, i + size));
  }
  return chunkedArr;
}

In the code above, we looped through arr and take the chunks with size given by size and push each array returned from slice into chunkedArr.

Therefore, if we call it as follows:

chunk([1, 2, 3, 4, 5, 6], 2)

We get:

[
  [
    1,
    2
  ],
  [
    3,
    4
  ],
  [
    5,
    6
  ]
]

compact

The compact method returns an array with the falsy values removed. Falsy values in JavaScript include false , 0, null , undefined , and NaN.

For instance, we can write the following code to implement compact:

const compact = (arr) => {
  return arr.filter(a => !!a);
}

All we had to do is call the filter method with the callback a => !!a which returns an array with all the truthy elements from the original array.

Then when we call it as follows:

compact([1, 2, 3, false, undefined])

We get:

[
  1,
  2,
  3
]

returned from our compact function.

concat

The Lodash concat method concatenates multiple arrays into one array and returns it. It works by reduce the nesting depth of nested arrays by one level and then putting them into the returned array.

For instance, we can write the following code to create our own concat method:

const concat = (arr) => {
  return arr.reduce((a, b) => a.concat(b), [])
}

In the code above, we used the reduce method to with the concat method to combine multiple arrays into one.

Array’s built-in concat method is useful for combining arrays. If we call our concat method with:

concat([1, 2, 3, [4],
  [
    [5]
  ]
])

We get:

[
  1,
  2,
  3,
  4,
  [
    5
  ]
]

like we did with the concat method. JavaScript array’s built-in concat method also reduces the nesting depth by 1.

difference

The difference method lets us find elements from a given array that’s not in another array.

We can implement or own equivalent function with JavaScript’s built-in array methods as follows:

const difference = (arr, arr2) => {
  return arr.filter(a => !arr2.includes(a));
}

In the code above, we have the difference method, which we implemented by using the filter method. In the callback that we passed into filter , we just return !arr2.includes(a) to find the items that aren’t in arr2.

drop

The drop method creates an array with a given number of elements dropped from the beginning.

For instance, we can implement it by writing:

const drop = (arr, n) => {
  return arr.slice(n);
}

We just pass in n straight to slice to return an array with the first n items removed from the original array.

Then when we call it as follows:

drop([1, 2, 3, 4, 5], 2)

We get:

[
  3,
  4,
  5
]

dropRight

The dropRight method is the opposite of drop . It returns an array with a given number of elements dropped from the right.

Again, we can use slice to implement dropRight as follows:

const dropRight = (arr, n) => {
  return arr.slice(0, -n);
}

We just pass in n multiplied by 1 to slice to return an array with the first n items removed from the original array.

Then when we call it as follows:

dropRight([1, 2, 3, 4, 5], 2)

We get:

[
  1,
  2,
  3
]

since the last 2 elements were removed from the returned array.

Conclusion

Many methods in Lodash can be implemented with plain JavaScript easily with a few method calls and operations.

We can loop through our array and use array’s slice method to implement chunk. The slice is also useful for drop and dropRight.

To implement compact, we just need to call filter with the callback that returns the truthy values.

Finally, to implement concat, we can use the array’s built-in concat method to do the concatenation repeatedly with reduce.

Categories
JavaScript

Useful Lodash Array Functions to Drop Items

Lodash is a utility library that has a lot of methods for manipulating arrays. In this article, we’ll look at useful Lodash array methods, including drop, dropRight, dropRightWhile, and dropWhile .

drop

The drop method creates a slice of an array with the first number of elements dropped from the beginning.

It takes 2 arguments which are an array to take the values from and the number of elements to drop from the beginning of the array in the first argument.

It returns a new array that drops the specified number of elements from the beginning.

For example, we can use it as follows:

import * as _ from "lodash";

const arr = [1, 2, 3, 4, 5];
const result = _.drop(arr, 2);

Then we get [3, 4, 5] assigned to result .

If the number is bigger than the length of the array, then we get an empty array returned. For example, we can write:

import * as _ from "lodash";

const arr = [1, 2, 3, 4, 5];
const result = _.drop(arr, 10);

Then we get [] assigned to result .

dropRight

The dropRight method is similar to the drop method, but returns an array with items dropped from the right instead of the left.

It takes 2 arguments which are an array to take the values from and the number of elements to drop from the end of the array in the first argument.

For example, we can write the following:

import * as _ from "lodash";

const arr = [1, 2, 3, 4, 5];
const result = _.dropRight(arr, 2);

Then we get [1, 2, 3] for result .

If the number is bigger than the length of the array, then we get an empty array returned. For example, we can write:

import * as _ from "lodash";

const arr = [1, 2, 3, 4, 5];
const result = _.dropRight(arr, 10);

Then we get [] assigned to result .

dropRightWhile

The dropRightWhile method returns an array with the items starting from the end removed until the predicate function that we passed in returns falsy.

It takes 2 arguments. The first is an array that we want to take the values from and remove the elements from the right. The second argument is the predicate function that has the array entry as the parameter and returns the condition that we want to be falsy when we want to stop removing items.

For example, given the following array:

const people = [
  { name: "Mary", age: 10 },
  { name: "Jane", age: 15 },
  { name: "John", age: 20 }
];

Then we can use dropRightWhile as follows:

import * as _ from "lodash";
const people = [
  { name: "Mary", age: 10 },
  { name: "Jane", age: 15 },
  { name: "John", age: 20 }
];
const result = _.dropRightWhile(people, p => p.age > 15);
console.log(result);

The code above will make a copy of the people array and remove the entries with age bigger than 15 starting from the end and return the resulting array.

Then we get:

[
  {
    "name": "Mary",
    "age": 10
  },
  {
    "name": "Jane",
    "age": 15
  }
]

Photo by Aaron Burden on Unsplash

dropWhile

dropWhile is similar to dropRightWhile . The only difference is that it removes items from the start that meets the given condition instead of from the right and returns that.

The arguments taken are the same as dropRightWhile .

For example, given the following array:

const people = [
  { name: "Mary", age: 10 },
  { name: "Jane", age: 15 },
  { name: "John", age: 20 }
];

Then we can use dropRightWhile as follows:

import * as _ from "lodash";
const people = [
  { name: "Mary", age: 10 },
  { name: "Jane", age: 15 },
  { name: "John", age: 20 }
];
const result = _.dropWhile(people, p => p.age < 15);
console.log(result);

The code above will make a copy of the people array and remove the entries with age less than 15 starting from the beginning and return the resulting array.

Then we get:

[
  {
    "name": "Jane",
    "age": 15
  },
  {
    "name": "John",
    "age": 20
  }
]

as the value assigned to result .

drop creates a slice of an array with the first number of elements dropped from the beginning. If the numbers dropped from the original array is bigger than the length of the array then it’ll return an empty array.

dropRight is the same as drop except the slice is created by removing items starting from the end.

dropRightWhile returns an array with the items starting from the end removed until the predicate function that we passed in returns falsy. dropWhile is similar to dropRightWhile except that the predicate is computed on values starting from the left.

Categories
JavaScript

More Lodash Features that are Available in Plain JavaScript

In recent years, new features in JavaScript have been rolling out at a rapid pace. The deficiencies that are filled in by other libraries before have become built-in features of plain JavaScript.

In this article, we’ll look at the methods in Lodash that are now available in plain JavaScript, like function currying, partially applied functions and more.

Some features are better with Lodash but for others, plain JavaScript will suffice.

Curry

The curry method in Lodash returns a function that has one or more arguments of the function originally passed in. We can use it as follows:

const subtract = (a, b) => a - b;
const currySubtract = _.curry(subtract);
const subtract1 = currySubtract(1);
const diff = subtract1(5);
console.log(diff);

In the code above, we defined the subtract function which returns the first parameter subtracted by the second.

Then we called the curry method with the subtract method passed in to create a new method that makes one argument and returns the subtract function with the first argument set by the parameter. That’s the currySubtract function.

Then we call the currySubtract to set the argument of the subtract function and return the function with the first argument set. Finally, we call the subtract1 function with the second argument of subtract to get the final result.

We can do the same thing with plain JavaScript by writing:

const currySubtract = a => b => a - b;
const subtract1 = currySubtract(1);
const diff = subtract1(5);
console.log(diff);

It does exactly the same thing, but without calling the curry method.

Partial

Lodash also has a method for partially applying a function, which is different from curry since some of the arguments of the function are passed into the function directly and the new function is returned.

For example, we can write the following:

const add = (a, b) => a + b;
const add1 = _.partial(add, 1);
const sum = add1(2);
console.log(sum);

The partial method passed in the first argument and returns the function with the first argument passed in. This gets us the add1 function.

Then when can call the add1 function with the second argument, which is 2 in the code above, and we get 3 for the sum .

In plain JavaScript, we can write:

const add = (a, b) => a + b;
const add1 = b => add(1, b);
const sum = add1(2);
console.log(sum);

Again, we can skip the Lodash partial method call like we did with the curry method call.

Eq

Lodash has the eq method to compare values. For example, we can write:

const equal = _.eq(1, 1);

It does the same thing as the Object.is, so we can just use that.

Photo by Dominik Lange on Unsplash

Add

It also has the add method, which we can use as we do in the following code:

const sum = _.add(1, 1);

We see the value is 2. It does the same thing as the + operator, so we can use that instead.

Nesting Operators

The good thing is that we can pass these methods straight into other Lodash methods like map and reduce as follows:

const mult = _.map([1, 2, 3], n => _.multiply(n, 2));

We get [2, 4, 6] from the code above, and we get 6 from:

const sum = _.reduce([1, 2, 3], _.add);

At

The at method lets us access the value of the properties of an object or an entry of an array by its index.

For example, given the following object, we can write the following:

const obj = { a: [{ b: { c: 2 } }, 1] };

We can get the value of the c property with at by writing:

const c = _.at(obj, ["a[0].b.c"]);

Then we get 2 for c .

Also, we can access more than one property of an object by passing more paths into the array above:

const vals = _.at(obj, ["a[0].b.c", "a[0].b"]);

Then we et:

2
{c: 2}

In JavaScript, we can access the paths directly:

const vals = [obj.a[0].b.c, obj.a[0].b];

However, it’s good for access paths that may not exist. For example, given the same object, if we write the following:

const vals = _.at(obj, ["a[0].b.c", "d.e"]);

Then we get undefined for the second entry instead of crashing the app.

As we can see, Lodash still has some advantages, with object path access. However, other operators like add, multiply, curry and partial, we can define easily with plain JavaScript ourselves, so Lodash still has some value.

Categories
JavaScript

Useful Lodash Array Functions — Extraction and Intersection

Lodash is a utility library that has lots of methods for manipulating objects. It has stuff that we use all the time and also things that we don’t use frequently or don’t think of using.

In this article, we’ll look at more useful Lodash array methods, including the head , indexOf , initial , intersection , intersectionBy , and intersectionWith methods.

head

The head method gets the first element of an array and returns it. first is an alias of head .

It takes an array as its only argument.

We can use it as follows:

import * as _ from "lodash";
const array = [1, 2, 3];
const result = _.head(array);
console.log(result);

Then we get 1 for result . head returns undefined is the array passed in is empty.

indexOf

indexOf gets the index of the first occurrence of the item found in the array that’s passed into the argument and returns it.

It takes up to 3 arguments. The first is the array to search. The second argument is the value to look for. The third is an optional argument for the index to start the search from.

For example, we can use it as follows:

import * as _ from "lodash";
const array = [1, 2, 3];
const result = _.indexOf(array, 2, 1);
console.log(result);

Then we get 1 since 2 is in the 2nd position and we search from the start.

initial

The initial method gets all but the last element of an array and returns it.

It takes an array as its only argument.

For example, we can use it as follows:

import * as _ from "lodash";
const array = [1, 2, 3];
const result = _.initial(array);
console.log(result);

Then we get [1, 2] for result .

intersection

The intersection method returns an array of values that are included in all given arrays. Equality comparison is done with the SameValueZero comparison which is the same as === except that NaN is considered equal to itself.

It takes a comma-separated list of arrays to return the intersection from.

For example, we can use it as follows:

import * as _ from "lodash";
const arr1 = [1, 2, 3];
const arr2 = [3, 4, 5];
const result = _.intersection(arr1, arr2);
console.log(result);

Then we get [3] since only 3 are present in both arr1 and arr2 .

intersectionBy

intersectionBy is like intersection except that it takes a function which is invoked for each element of each array to generate the criterion for which items are compared. The first array determines the order and reference of results.

It takes a comma-separated list of arrays as arguments and a function for the criterion to compare to find the intersection with or a string with the property name to compare.

For example, we can use it as follows:

import * as _ from "lodash";
const arr1 = [
  { name: "Joe", age: 10 },
  { name: "Mary", age: 12 },
  { name: "Jane", age: 13 }
];
const arr2 = [
  { name: "Joe", age: 10 },
  { name: "Jerry", age: 12 },
  { name: "Amy", age: 13 }
];
const result = _.intersectionBy(arr1, arr2, a => a.name);
console.log(result);

Then we get:

[
  {
    "name": "Joe",
    "age": 10
  }
]

for result .

We can replace a => a.name with 'name' as follows:

import * as _ from "lodash";
const arr1 = [
  { name: "Joe", age: 10 },
  { name: "Mary", age: 12 },
  { name: "Jane", age: 13 }
];
const arr2 = [
  { name: "Joe", age: 10 },
  { name: "Jerry", age: 12 },
  { name: "Amy", age: 13 }
];
const result = _.intersectionBy(arr1, arr2, "name");
console.log(result);

Then we get the same thing.

intersectionWith

intersectionWith is like intersection except that it takes a comparator function as the last argument. The parameters for the function are 2 entries of from the arrays to compare against.

It takes a comma-separated list of arrays as arguments and the comparator function as the last argument.

For example, we can use it as follows:

import * as _ from "lodash";
const arr1 = [
  { name: "Joe", age: 10 },
  { name: "Mary", age: 12 },
  { name: "Jane", age: 13 }
];
const arr2 = [
  { name: "Joe", age: 10 },
  { name: "Jerry", age: 12 },
  { name: "Amy", age: 13 }
];
const result = _.intersectionWith(arr1, arr2, (a, b) => a.name === b.name);
console.log(result);

Then we get:

[
  {
    "name": "Joe",
    "age": 10
  }
]

for result .

The head method gets the first element of an array and returns it. first is an alias of head .

indexOf gets the index of the first occurrence of the item found in the array that’s passed into the argument and returns it. It can take a starting index to search from which defaults to 0.

initial gets all but the last element of an array and returns it.

To find array entries that are in all arrays, we can use the intersection , intersectionBy , and intersectionWith methods. They differ in that they may take functions for the criterion to compare or a comparator method to compare for equality respectively.

Categories
JavaScript

Useful Lodash Array Functions — Fill and Find

Lodash is a utility library that has lots of methods for manipulating objects. It has stuff that we use all the time and also things that we don’t use frequently or don’t think of using.

In this article, we’ll look at more useful Lodash array methods, including fill , findIndex , and findLastIndex .

fill

The fill method fills elements of an array with value from the start index inclusive but not including the end index.

It takes up to 4 arguments. The first argument is the array to fill in the items into. The second is the value to fill the array with.

The third is an optional argument for the start index to fill entries with. The default value is 0.

The last argument is an optional argument for the end index to fill it up to. The default value is the array ‘s length .

It returns a new array with the filled entries.

For example, we can use it as follows:

import * as _ from "lodash";

const result = _.fill(new Array(5), 1, 0, 2);
console.log(result);

Then we get:

[
  1,
  1,
  null,
  null,
  null
]

and assigned to result. Entries that aren’t filled are null .

If the end is bigger than the array’s length , as in the following code:

import * as _ from "lodash";

const result = _.fill(new Array(5), 1, 0, 10);
console.log(result);

Then we get all the arrays filled:

[
  1,
  1,
  1,
  1,
  1
]

and assigned to result. We can also fill items in the middle of an array as follows:

import * as _ from "lodash";

const result = _.fill(new Array(5), 1, 1, 2);
console.log(result);

Then we get:

[
  null,
  1,
  null,
  null,
  null
]

and assigned to result.

Photo by Gabrielle Costa on Unsplash

findIndex

The findIndex method gets the first match of an object from an array that satisfies a given condition.

It takes up to 3 arguments. The first is the array to search for items with. The second is an optional argument where we pass in the callback function that returns the condition to look for. Finally, the third argument is an optional argument to specify where to start.

It returns the index of the entry if a match is found. Otherwise, it returns -1.

We can use it as follows:

import * as _ from "lodash";

const people = [
  { name: "Joe", age: 10 },
  { name: "Mary", age: 12 },
  { name: "Jane", age: 13 }
];
const result = _.findIndex(people, p => p.age === 10);

Then we get 0 for result.

We can also pass in a starting index as follows:

import * as _ from "lodash";

const people = [
  { name: "Joe", age: 10 },
  { name: "Mary", age: 12 },
  { name: "Jane", age: 13 }
];
const result = _.findIndex(people, p => p.age === 10, 1);

Then we get -1 since nothing from the index 1 and on has an entry with age 10.

findLastIndex

This is similar to findIndex but it finds the last match instead of the first match. The search is also done from end to start.

The arguments are the same as the same as findIndex , except that the third argument takes the end index which too starts the search from the index of the first index.

For example, we can use it as follows:

import * as _ from "lodash";

const people = [
  { name: "Joe", age: 10 },
  { name: "Mary", age: 12 },
  { name: "Jane", age: 13 }
];
const result = _.findLastIndex(people, p => p.age === 12);

Then we get 1 for result since the entry match the condition is in the 2nd entry.

We can also pass in the end index as the third argument. For example, we can write:

import * as _ from "lodash";

const people = [
  { name: "Joe", age: 10 },
  { name: "Mary", age: 12 },
  { name: "Jane", age: 13 }
];
const result = _.findLastIndex(people, p => p.age === 13, 1);

Then we get -1 since the search starts at index 1 and goes down to 0. Nothing in index 1 or less meets the condition, so we get -1.

The fill method fills elements of an array with value from the start index inclusive but not including the end index.

The findIndex method gets the first match of an object from an array that satisfies a given condition and returns the index of that entry.

findLastIndex is similar to findIndex but it finds the last match instead of the first match. The search is also done from the end index to the start.