JavaScript Higher Order Functions with React

Let’s talk about 3 useful ES7 JavaScript methods today and how you can use them in React:

  • .map()
  • .find()
  • .reduce()

We’ll explore the why and how to use them.

Why?

They’re extremely useful methods that, once you understand how to use it, you’ll never go back! These methods will help with your productivity and efficiency. In my opinion, they’re essential to building a react application. 

Getting started with .map():

Time to jump right in and see how .map() works with this example:

let array = [1,2,3,4,5];
let arrayMapped = array.map(num => num*2);

//array = [1,2,3,4,5]
//arrayMapped = [2,4,6,8,10]

.map() iterates through an array with each element (num) and runs a function on it (num * 2). Finally it returns the array after the function is run on it.

A simple realistic use of .map():

Now that you’ve seen how .map works, let’s look at a more realistic use of .map() that you could implement in React. Let’s say you had an array of products that you wanted to generate a react component out of each product, here’s a quick way to do this.

{products.map((product) => (
  <div key={product.id}>
    <p>Product: {product.name}</p>
    <p>Product: {product.description}</p>
  </div>
)}

Getting started with .find():

The .find() method returns the value of the first element that satisfies the provided comparison test.

let array = [1,2,3,4,5];
let evenNum = array.find(num => num % 2 === 0)

//array = [1,2,3,4,5]
//evenNum = 2

As you can see above, it only returns the first element that is even.

If you’re looking for the index instead of the value, take a look at .findIndex() instead.

Using .find() in React:

In this example, we have a product where many users has liked this product but we only want one user that matches a user id.

let userFound = product.likes.find(user => user.id === userid)

<div key={userFound.id}>
  <p>User that liked this product: {userFound.name}</p>
  <p>UserFound's age: {userFound.age}</p>
</div>

Getting started with .reduce():

Last but not least, let’s take a look at .reduce():

//Accepts a function that iterates through a given array and outputs a new array with the function completed on each element.
let array = [1,2,3,4,5];

const sumOfArray = (sum, num) => {
  return sum + num;
}

let arrayReduced = array.reduce(sumOfArray);

//array = [1,2,3,4,5];
//arrayReduced = [15];

Here we have our array of numbers, as per normal, and a function called sumOfArray which takes the sum and num arguments. We then use .reduce() which iterates through the elements of the array and adds the elements to return an array after the function is run on it.

It’s important to note the arguments and order of these arguments in this reducer function:

array.reduce( function(total, currentValue, currentIndex, arr) )
  1. total – The initial value or the previously returned value (required)
  2. currentValue – The value of the current element (required)
  3. currentIndex – Index of the current element (optional)
  4. arr – Original/Source array (optional)

A more complicated use of .reduce():

Let’s use our example of products here again and we would like to re-arrange them into an array per category.

const sortProductsByCategories = products => {
  // sorts all products and reduces them into categories
  const productsSorted = products.sort((a, b) => {
    return a.category.localeCompare(b.category);
  });
  //For each category, we have an array of products.
  return Object.entries(
    productsSorted.reduce((products, product) => {
      const category = product.category;
      products[category] = products[category]
        ? [...products[category], product]
        : [product];
      return products;
    }, {})
  );
};

const productsByCategories = sortProductsByCategories(products);

//Next we'll use what we learned with .map() and visualize it in a React component
{productsByCategories.map(([category, products]) => (
  <div key={category}>
    <h3>{category}</h3>
    {products.map(product => (
      <div key={product.id}>
        <p>Product: {product.name}</p>
        <p>Description: {product.description}</p>
      </div>
    ))}
    <br />
  </div>
))}

The End

In summary, there’s a multitude of things you can do with these three higher order functions. Start imagining the possibilities!

Thanks for taking the time to read my first blog post! I would love to hear what you thought of it, so feel free to leave a comment. Any feedback is appreciated and welcomed.