2024

Built-in functions

In 2019, JavaScript has some amazing and readily accessible built-in functions. Learning React has been one thing, but adding various built-in JavaScript functions to my repertoire has been―arguably―even more rewarding.

Functions such as Array.map, Array.filter, and Array.reduce, can make code so much more straight forward. Of all the tools I've equipped, I've found Array.reduce to be the most confounding. I'd heard of accumulation before, but I'd never heard of an "accumulator" (thanks, MDN Documentation). Of the lot, it's probably the most powerful.

Below is a mostly real example of a situation where I needed to build a quick set of item filter links based on an array of objects returned from an API.

const products = props.productsFromAnAPI;             // array of objects with a 'type' property

const productTypes = [{ type: 'all' }]                // add an artificial product item to the start of the
  .concat(products)                                   // products array, as real data won't have an 'all' type
  .reduce((accumulator, currentValue) => {
    if (!accumulator.includes(currentValue.type)) {   // check the previously accumlated items and only add
      return [                                        // to the array if it's not yet included
        ...accumulator,
        currentValue.type                             // ⚠️ performance tip: this example returns a new array
    ];                                                // with every itteration - for large arrays, consider accumulator.push()
    } else {
      return accumulator;                             // item included already, return the array as is
    }
  }, [])                                              // initialise with an empty array
  .map((type, t) => {
    return (
      <li key={t}>
        <NavLink to={`/store/filter/${type}`}>
          {type}
        </NavLink>
      </li>
    );
  });