DEV Community

Ioannis Potouridis
Ioannis Potouridis

Posted on

Implementing common array methods with the reduce method

Instead of inventing the CTRL-F for notebooks or the CTRL+Z of scissors I decided to do something more challenging and interesting. I am a developer. I write articles about array methods.

It's almost three years since I have started programming with JavaScript and I felt confident to say that you can replicate any array method with the reduce method.

The only caveat is that some of the methods return the first element when predicate returns true and you cannot escape the iteration of a reduce method, at least not the one that Array.prototype provides.

every is one of those methods. every checks if the callback (predicate) returns true for all elements (collection). Here is a lodish (Latin: lodashish) implementation with the reduce method:

function every(collection, predicate) {
  return collection.reduce((prev, curr, index) => {
    return predicate(curr, index, collection) && prev;
  }, true);
}

We set the initial value of the accumulator to true and check the current element AND the previous accumulated value (AND is true if and only if all of its operands are true).

Similar to every, some's iteration is stopped once predicate returns true, but it returns true if any of the element checks returns true. Here is its implementation:

function some(collection, predicate) {
  return collection.reduce((prev, curr, index) => {
    return predicate(curr, index, collection) || prev;
  }, false);
}

The initial accumulator's value is set to false and we check each element against the previous result using the OR operator (OR is true if any of its arguments are true).

filter and map seem to be more frequently used than every and some, which is why I feel we can skip their explanation. Here is the lodish implementation with the reduce method:

function filter(collection, predicate) {
  return collection.reduce((prev, curr, index) => {
    if (predicate(curr, index, collection)) {
      prev.push(curr);
    }

    return prev;
  }, []);
}
function map(collection, iteratee) {
  return collection.reduce((prev, curr, index) => {
    prev.push(iteratee(curr, index, collection));

    return prev;
  }, []);
}

find is another popular array method. It returns the first element that predicate returns true else it returns undefined.

function find(collection, predicate) {
  return collection.reduce((prev, curr, index) => {
    if (predicate(curr, index, collection)) {
      return prev || curr;
    }

    return prev;
  }, undefined);
}

Lastly, findIndex is like find but it returns the matched element's index instead of the element. It returns -1 otherwise.

function findIndex(array, predicate) {
  return array.reduce((prev, curr, index) => {
    if (predicate(curr, index, array)) {
      return index;
    }

    return prev;
  }, -1);
}

Latest comments (0)