Categories
Lodash

Lodash Methods Implemented with Plain JavaScript — Accessing Array Items

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 look at how to implement Lodash array methods that are used to access array items.

findIndex

The findIndex method in Lodash takes an array and then returns the first index of the array item with the given condition.

JavaScript’s standard library already has the findIndex method already. The difference between the Lodash and plain JavaScript version is that the Lodash one can also accept an index for where we can start searching as follows:

const findIndex = (arr, condition, start) => arr.findIndex((a, i) => condition(a) && i >= start)

In the code above, we have our own findIndex method, which takes the following arguments:

  • arr — the original array to call findIndex with
  • condition — the condition to check, which is a callback that takes an array and returns the condition that matches the condition
  • start — which is the starting index of arr to search for items

In the code above, we just called the JavaScript’s built-in findIndex method with a callback that returns the result of condition(a) && i >= start .

This will start searching arr from the start index and the given condition .

Then we can call it as follows:

const index = findIndex([1, 2, 3, 4, 5], a => a > 2, 1)

which means that index should equal 2 since that’s the first array entries that bigger than 2.

findLastIndex

findLastIndex is like findIndex , but searches the array from the end instead of the beginning. The arguments are the same as findIndex except the start index searches towards the beginning instead of the end.

For instance, we can implement it as follows:

const findLastIndex = (arr, condition, start) => {
  for (let i = arr.length - 1; i >= 0; i--) {
    if (condition(arr[i]) && i <= start) {
      return i;
    }
  }
  return -1;
}

In the code above, we implemented the findLastIndex method with a for loop instead of the array’s findIndex method.

If we found the array that meets the condition condition(arr[i]) && i <= start then we return that index since we’re searching from the end towards the beginning for an entry that returns true if we call condition(arr[i]) .

If the loop finished without finding an element, then we return -1. Therefore, when we have:

const lastIndex = findLastIndex([1, 2, 3, 4, 5], a => a > 2, 1)

Then lastIndex is 4 because findLastIndex searches from the end and find one that’s between index 0 and and start .

first

The Lodash’s first method, which is the alias of the head method, takes an array and returns the first entry from it. We can just access the first entry of an array with its index, so we can implement first or head easily as follows:

const first = arr => arr[0]

In the code above, we just use [0] to get the first index of an array.

flatten

Fortunately, there’s already a flat method in plain JavaScript, which can flatten an array by any level.

For instance, we can write the following code to implement Lodash’s flatten , which flattens the given array one level deep:

const flatten = arr => arr.flat(1)

We just called the flat method with 1 to flatten an array one level deep.

Therefore, when we call our flatten function as follows:

const flattened = flatten([1, [2], 3, 4, 5])

We get that flattened is [1, 2, 3, 4, 5] .

Also, we can use the spread operator to implement flatten as follows:

const flatten = arr => {
  let flattened = [];
  for (const a of arr) {
    if (Array.isArray(a)) {
      flattened = [...flattened, ...a];
    } else {
      flattened.push(a);
    }
  }
  return flattened;
}

We looped through the entries of arr and then spread it into a new array if it’s an array. Otherwise, we push to push the entry into the end of the returned array.

Then we get the same result as before.

Conclusion

Lodash’s findIndex can be implemented by the JavaScript array’s findIndex method, which finds the index but we can’t specify what index to start the search with.

To implement the findLastIndex method, we have to use a plain for loop since we have to loop through an array in reverse.

The first method can be implemented by returning arr[0]. Finally, the flatten method can be implemented with the spread operator after we check if the entry is an array with the Array.isArray method. Otherwise, we can use the push method.

Categories
Lodash

Learning JavaScript by Implementing Lodash Methods — Objects and Collections

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 how to implement methods for checking if something exists in a collection and dealing with objects.

some

The Lodash some method returns a boolean to indicate if an item that meets the condition in the predicate exists in a collection.

For arrays, we can use the plain JavaScript array’s some method to search for an item and returns true is the item with the given condition is found.

We can implement some with the plain JavaScript’s some method as follows:

const some = (collection, predicate) => {
  return collection.some(predicate);
}

In the code above, we just used the array instance’s some method and pass in the predicate .

Then when we run some as follows:

const users = [{
    'user': 'foo',
    'active': true
  },
  {
    'user': 'bar',
    'active': false
  }
];
const result = some(users, u => u.active);

result is true since there’s an entry of users with active set to true .

castArray

The Lodash castArray method converts any object to an array. It takes a list of arguments and puts them all in an array.

With the rest operator, we can put the items in an array without much work. We can implement the castArray method as follows:

const castArray = (...args) => args;

In the code above, we just used the rest operator with args , which converts the list of arguments to an array, and then returned it directly.

Then when we call our castArray function as follows:

const result = castArray(1, 2, 3);

Then we get that result is:

[
  1,
  2,
  3
]

clone

The Lodash clone method returns a shallow copy of an object. It supports cloning all kinds of objects, including arrays, buffers, booleans, and date objects.

Since JavaScript has the spread operator for objects, we can just use that to do the cloning as follows:

const clone = obj => ({
  ...obj
});

Then we can call the clone function as follows:

const result = clone({
  a: 1
});

Then we see that result is:

{
  "a": 1
}

cloneDeep

The Lodash cloneDeep method recursively clones an object. With the spread operator, we can just recursively clone each level of an object ourselves.

For instance, we can implement that as follows:

const cloneDeep = (obj, cloned = {}) => {
  if (Array.isArray(obj)) {
    cloned = [
      ...obj
    ];
    for (let i = 0; i < obj.length; i++) {
      cloneDeep(obj[i], cloned[i]);
    }
  } else if (typeof obj === 'object') {
    cloned = {
      ...obj
    };
    for (const p of Object.keys(obj)) {
      cloneDeep(obj[p], cloned[p])
    }
  }
  return cloned;
}

In the code above, we have our own cloneDeep function, which takes obj for the original object and the cloned object which has the cloned object.

We loop through the objects and call cloneDeep on them afterward.

If obj is an array, then we spread the array with the spread operator.

Otherwise, we can use the spread operator to clone obj into cloned at the top level.

Then we check that if obj is an object. If it is, then we can loop through the keys and calls cloneDeep in the lower level of an object.

In the end, we return cloned with the cloned object.

Then we can call our cloneDeep function as follows:

const obj = {
  a: 1,
  b: {
    c: 2
  }
}
const result = cloneDeep(obj);

Then we get that result is:

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

and:

result === obj

is false . We can also clone arrays as follows:

const obj = [{
  'a': 1
}, {
  'b': 2
}]
const result = cloneDeep(obj);

Then we get that result is the following array:

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

and:

result === obj

is still false .

Conclusion

We can use the plain JavaScript array’s some method to check if an object that meets the condition in a predicate exists in a collection.

To implement the castArray method, we can just use the rest operator on the arguments.

Finally, the clone and cloneDeep methods can be implemented with the spread operator. cloneDeep needs an array or object check before cloning each level.

Categories
Lodash

Plain JavaScript of Lodash Array Methods

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 how to implement a few Lodash methods with plain JavaScript.

dropRightWhile

The dropRightWhile function lets us create a slice of an array starting from the right until a condition is met. The condition is determined by a callback.

We can implement it as follows with plain JavaScript as follows:

const dropRightWhile = (arr, condition) => {
  const newArr = [];
  for (let i = arr.length - 1; i >= 0; i--) {
    if (condition(arr[i])) {
      return newArr;
    }
    newArr.push(arr[i]);
  }
  return newArr;
}

In the code above, we have a for loop that’s looped through in reverse. If the condition function, which takes an array entry as the value returns true , then we return newArr , which has the items that are pushed into the array that we want to keep.

If the loop finishes without returning newArr , then it’ll also return newArr .

Therefore, when we have:

const arr = [1, 2, 3]
const dropped = dropRightWhile(arr, (a) => a === 2)

We get that dropped is [3] since we stopped the function when the callback condition is met, which is when an array entry is 2.

dropRightWhile can also take a string with the key name to check if it’s true before returning the sliced array.

We can add that check easily with the following code:

const dropWhile = (arr, key) => {
  const newArr = [];
  for (let i = arr.length - 1; i >= 0; i--) {
    if (arr[i][key]) {
      return newArr;
    }
    newArr.push(arr[i]);
  }
  return newArr;
}

Then when we have the following array and call it as follows:

const arr = [{
    name: 'foo',
    active: false
  },
  {
    name: 'bar',
    active: true
  },
  {
    name: 'baz',
    active: false
  }
]
const dropped = dropRightWhile(arr, 'active');

We get:

[
  {
    "name": "foo",
    "active": false
  }
]

since we return the array where we push the entries from the right until active is true .

dropWhile

dropWhile is the opposite of dropRightWhile . It gets a slice of an array by starting from the beginning and pushing those items into a new array, and returning it either when the loop finishes or when the condition in the callback returns true .

Like dropRightWhile , the callback takes an array entry. For instance, we can implement it ourselves as follows:

const dropWhile = (arr, condition) => {
  const newArr = [];
  for (const a of arr) {
    if (condition(a)) {
      return newArr;
    }
    newArr.push(a);
  }
  return newArr;
}

In the code above, we used the for...of loop instead of a regular for loop since we’re just looping through arr forward, which can be done easily with for loop.

dropWhile can also take a string with the key name to check if it’s true before returning the sliced array.

We can add that check easily with the following code:

const dropWhile = (arr, key) => {
  const newArr = [];
  for (const a of arr) {
    if (a[key]) {
      return newArr;
    }
    newArr.push(a);
  }
  return newArr;
}

Then when we have the following array and call it as follows:

const arr = [{
    name: 'foo',
    active: false
  },
  {
    name: 'bar',
    active: true
  },
  {
    name: 'baz',
    active: false
  }
]
const dropped = dropWhile(arr, 'active');

We get:

[
  {
    "name": "foo",
    "active": false
  }
]

since we return the array where we push the entries until active is true .

fill

The fill method fills the element of an array with values from the start but not up to the end index by replacing the values from the original array with the one that we provide starting from a starting index and ending with the end index.

We can implement fill as follows:

const fill = (arr, value, start, end) => arr.fill(valu, start, end)

In the code above, we have 4 arguments like the Lodash’s fill method, which are arr for the original array, value which is the value we want to fill the array with. start , which is the starting index of array entry we’re replacing, and end , which is the end index of the array we’re replacing the values with.

Then when we call the fill as follows:

const filled = fill([1, 2, 3, 4, 5], 8, 0, 3);

We get that filled is:

[8, 8, 8, 4, 5]

As we can see, the array instance’s fill method does the same job as Lodash’s fill .

Conclusion

We can implement dropWhile , dropRightWhile , and fill easily with plain JavaScript’s array methods. With a few lines of code, we eliminated the need to use Lodash array methods.

Categories
Lodash

Plain JavaScript versions of Lodash Array Filtering and Manipulation Methods

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.

We can implement the pullAllBy , pullAllWith , pullAt , and remove methods easily with plain JavaScript.

pullAllBy

The pullAllBy returns an array that removes the given values that matches the items we want to remove after converting them with the iteratee function.

We can implement it as follows:

const pullAllBy = (arr, values, iteratee) => arr.filter(a => !values.map(iteratee).includes(iteratee(a)))

In the code above, we call the given iteratee function to map the values before doing the comparison with includes . Also in includes , we also call iteratee to do the same conversion so that they can be compared properly.

Then we can use our pullAllBy function as follows:

const result = pullAllBy([1, 2.1, 3], [2.2, 3], Math.floor)

And we get [1] for result .

pullAllWith

The Lodash pullAllWith method takes a comparator instead of the iteratee to compare the values to exclude with the comparator instead of an iteratee to convert the values before comparing them.

For instance, we can implement it as follows:

const pullAllWith = (arr, values, comparator) => arr.filter(a => values.findIndex((v) => comparator(a, v)) === -1)

In the code above, we use the plain JavaScript’s findIndex method with a callback that calls the comparator to compare the values.

We call filter to filter out them items that are included with the values array.

Then when we call it as follows:

const result = pullAllWith([1, 2, 3], [2, 3], (a, b) => a === b)

We get [1] for result .

pullAt

The Lodash pullAt method returns an array with the elements with the items with the given indexes.

It also removes the elements in-place with those indexes.

Again, we can use the filter method to filter out the items that we want to remove as follows:

const pullAt = (arr, indexes) => {
  let removedArr = [];
  const originalLength = arr.length
  for (let i = 0; i < originalLength; i++) {
    if (indexes.includes(i)) {
      removedArr.push(arr[i]);
    }
  }

  for (let i = originalLength - 1; i >= 0; i--) {
    if (indexes.includes(i)) {
      arr.splice(i, 1);
    }
  }
  return removedArr.flat()
}

In the code above, we used a for loop to loop through the array and call splice on arr on the items with the given index in the indexes array.

Then we push the removed items into the removedArr array.

We then have and 2nd loop, which loops arr in reverse so that it doesn’t change arr ‘s indexes before we call splice on it.

In the loop, we just call splice to remove the items with the given index.

Finally, we call flat to flatten the array since splice returns an array.

Therefore, when we call it as follows:

const arr = [1, 2, 3]
const result = pullAt(arr, [1, 2])

We see that result is [2, 3] since we specified [1, 2] in the array with the index to remove and arr is now [1] since that’s the only one that’s not removed.

remove

The remove method removes the items from an array in place with the given condition and returns the removed items.

We can implement it ourselves with the for loop as follows:

const remove = (arr, predicate) => {
  let removedArr = [];
  const originalLength = arr.length
  for (let i = 0; i < originalLength; i++) {
    if (predicate(arr[i])) {
      removedArr.push(arr[i]);
    }
  }
  for (let i = originalLength - 1; i >= 0; i--) {
    if (predicate(arr[i])) {
      arr.splice(i, 1);
    }
  }
  return removedArr.flat();
}

In the code above, we have 2 loops as we have with the pullAt method. However, instead of checking for indexes, we’re checking for a predicate .

Like pullAt , we have to loop through the array indexes in reverse to avoid splice changing the indexes as we’re looping through the items of arr .

Then when we call remove as follows:

const arr = [1, 2, 3]
const result = remove(arr, a => a > 1)

We get that result is [2, 3] and arr is [1] since we specified that the predicate is a => a > 1 , so anything bigger than 1 is removed from the original array and the rest are returned.

Conclusion

The pullAt and remove methods are very similar, except that pullAt takes an array of index and remove takes a callback with the given condition.

pullAllBy and pullAllWith are implemented with the filter method. pullAllBy also needs to map the values with the iteratee function before doing comparisons.

Categories
Lodash

Learning JavaScript by Implementing Lodash Methods — Objects

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 some Lodash object methods that we can implement ourselves in plain JavaScript.

forInRight

The forInRight method loops through the own and inherited properties of an object in reverse order. In each iteration, it calls the iteratee function with the value, key, and object arguments until it returns false . Then the loop will end.

value is the value of the object property that’s being looped through. key is the key of the property that’s being looped through, and object is the object where the properties are being traversed.

We can implement that ourselves by using the for...in loop to get all the keys in the order that it returns and put them in an array.

Then we can reverse the keys by calling the array instance’s reverse method and use the for...of loop to loop through the keys:

const forInRight = (object, iteratee) => {
  const keys = [];
  for (const key in object) {
    keys.push(key);
  }
  const reversedKeys = keys.reverse();
  for (const key of reversedKeys) {
    const result = iteratee(object[key], key, object);
    if (result === false) {
      break;
    }
  }
}

In the code above, we first used the for...in loop to loop through the keys of an object forward and put them all in the keys array.

In the for...in loop, we push the keys into the keys array. Then we reverse the keys that are in keys array by calling reverse and then assign the reversed array as the value of reversedKeys .

Then we can use the for...of loop to loop through reversedKeys and then call iteratee with object[key], key, and object . We assigned the returned value of iteratee to result .

When result is false , we break the loop.

Now when we call it with the Foo constructor as follows:

function Foo() {
  this.a = 1;
  this.b = 2;
}

Foo.prototype.c = 3;

forInRight(new Foo(), (value, key) => console.log(key));

We get that we get back c , b and a as the logged values in that order.

findKey

The Lodash findKey finds the first property of an object where the predicate returns true .

We can implement that by traversing the items of an object and call the predicate function to check if the given property value matches the condition returned by the predicate .

For instance, we can implement that as follows:

const findKey = (object, predicate) => {
  for (const key of Object.keys(object)) {
    if (predicate(object[key])) {
      return key
    }
  }
}

In the code above, we used Object.keys to get the own keys of object . Then we looped through the keys with the for...of loop.

Inside the loop, we call predicate with the value of the object to see if it meets the condition defined in the preicate function.

Then when we run the findKey function as follows:

const users = {
  'foo': {
    'age': 15,
    'active': true
  },
  'bar': {
    'age': 30,
    'active': false
  },
  'baz': {
    'age': 1,
    'active': true
  }
};

const result = findKey(users, o => o.age < 40);

We have the users object with multiple keys with an object with the age and active properties as the value.

Then we called findKey with it and the predicate function set to o => o.age < 40 .

We then get that 'foo' is the value of result .

findLastKey

Lodash’s findLastKey function is like findKey except the keys are looped over in the opposite order of it.

To implement it, we can just change our findKey implement by calling the reverse method on the keys array returned by Object.keys .

We can do that as follows:

const findLastKey = (object, predicate) => {
  for (const key of Object.keys(object).reverse()) {
    if (predicate(object[key])) {
      return key
    }
  }
}

Then we call our findLastKey function as follows:

const users = {
  'foo': {
    'age': 15,
    'active': true
  },
  'bar': {
    'age': 30,
    'active': false
  },
  'baz': {
    'age': 1,
    'active': true
  }
};

const result = findLastKey(users, o => o.age < 40);

We get 'baz' as the value of result instead of 'foo' since we looped through the keys in reverse.

Conclusion

The forInRight method can be implemented by putting the own and inherited in an array by looping through them with the for...in loop and then pushing them in the array.

Then we can loop through them with the for...of loop and call the iteratee function on it.

The findKey and findKeyRight functions can be implemented by looping through the keys and then calling the predicate function on it.