<< Back to main

Javascript Recursive Array Functions

A set of functions that shows how we can recreate array functions without loops utilizing recursion instead.

Un conjunto de funciones que muestra cómo podemos recrear funciones de matriz sin bucles, usando recursividad en su lugar.

Map

/**
 * Map through each one of the items and transform them using the callback function
 */
function map(array, callback) {
  if (array.length <= 0) return array;
  return [callback(array[0]), ...map(array.slice(1), callback)];
}

Usage

console.log(
  "Map:",
  map([1, 2, 3], function (item) {
    return item * 2;
  })
);

Reduce

/**
 * Reduce each one of the items and add them to the accumulator using the callback function
 */
function reduce(array, callback, prevState) {
  if (array.length <= 0) return prevState;
  return reduce(array.slice(1), callback, callback(prevState, array[0]));
}

Usage

console.log(
  "Reduce:",
  reduce(
    [1, 2, 3],
    function (accumulator, item) {
      return accumulator + item;
    },
    0
  )
);

Filter

/**
 * Filter the items of the array based on the callback function
 */
function filter(array, callback) {
  if (array.length === 0) return [];
  if (callback(array[0])) {
    return [array[0], ...filter(array.slice(1), callback)];
  }
  return filter(array.slice(1), callback);
}

Usage

console.log(
  "Filter:",
  filter([1, 2, 3, 4, 5, 6, 7], function (item) {
    return item % 2 !== 0;
  })
);

Find

/**
/**
  * Find one of the items and return it based on the callback function
  */
function find(array, callback) {
  if (array.length === 0) return null;
  if (callback(array[0])) return array[0];
  return find(array.slice(1), callback);
}

Usage

console.log(
  "Find:",
  find([1, 2, 3], function (item) {
    return item > 2;
  })
);