<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: DAZ</title>
    <description>The latest articles on DEV Community by DAZ (@daz4126).</description>
    <link>https://dev.to/daz4126</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F989022%2Ffa56dcbd-3658-4a3c-9e53-7d59e72d7651.png</url>
      <title>DEV Community: DAZ</title>
      <link>https://dev.to/daz4126</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/daz4126"/>
    <language>en</language>
    <item>
      <title>How to use Array.map to render a list of items in React</title>
      <dc:creator>DAZ</dc:creator>
      <pubDate>Sat, 17 Dec 2022 16:12:22 +0000</pubDate>
      <link>https://dev.to/daz4126/how-to-use-arraymap-to-render-a-list-of-items-in-react-4d01</link>
      <guid>https://dev.to/daz4126/how-to-use-arraymap-to-render-a-list-of-items-in-react-4d01</guid>
      <description>&lt;p&gt;One of the most common tasks for React developers is to render a list of data (e.g. users) onto a web page. And thanks to the the &lt;code&gt;Array.map&lt;/code&gt; method this can be done in a simple and efficient way. In this article, you'll learn how JSX helps to make components in React as close to HTML as possible while still allowing you to write some JavaScript.&lt;/p&gt;

&lt;p&gt;Let's start by looking at how to use JSX to render dynamic data to the page using React. If you want to insert a dynamic value into the HTML you can place an expression inside curly braces like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;h1&amp;gt;Hello {name}!&amp;lt;/h1&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is all fairly straightforward, but eventually you'll run into a situation where you want to insert a list of data into a component. Lists of data are fairly common in websites and apps, for example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  lists of tweets on Twitter&lt;/li&gt;
&lt;li&gt;  playlists of videos on YouTube&lt;/li&gt;
&lt;li&gt;  lists of photos on Instagram for example&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And when you need to display insert a list of values in React, the &lt;code&gt;Array.map&lt;/code&gt; function will become your new best friend!&lt;/p&gt;

&lt;h2&gt;
  
  
  Why not use for loops instead of map? 🤔
&lt;/h2&gt;

&lt;p&gt;The reason for this is that you can't use &lt;code&gt;for&lt;/code&gt; loops in JSX. This is because anything inside the curly braces in a component has to be an expression: which means you can't use imperative statements like &lt;code&gt;for&lt;/code&gt; or &lt;code&gt;if&lt;/code&gt;. But don't worry, JavaScript arrays have some powerful methods that will help you transform the data into a value that can be inserted directly into components.&lt;/p&gt;

&lt;h2&gt;
  
  
  How does map work?
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Array.map&lt;/code&gt; works in a similar way as a mathematical function.&lt;/p&gt;

&lt;p&gt;Take a look at the diagram below (from &lt;a href="https://www.mathsisfun.com/sets/function.html"&gt;Maths Is Fun&lt;/a&gt;). It's a mathematical function mapping one set of numbers on the left, to another set of numbers on the right. The mapping is applying a rule to each number. Can you figure out what this rule is?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qZ4jOmLb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://scrimba.com/articles/content/images/2022/11/Array-Mapping---how-it-works.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qZ4jOmLb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://scrimba.com/articles/content/images/2022/11/Array-Mapping---how-it-works.png" alt="https://www.mathsisfun.com/sets/images/function-sets-x2.svg" width="880" height="575"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hopefully you figured out that the rule is to square the number on the left (i.e. multiply it by itself) to get the number on the right. In mathematical notation, this would be written as:&lt;/p&gt;

&lt;p&gt;n → n² &lt;/p&gt;

&lt;p&gt;(note how similar this looks to an arrow function in JavaScript by the way).&lt;/p&gt;

&lt;p&gt;An array of values in JavaScript can be thought of as the sets of numbers used in the example above. The &lt;code&gt;Array.map&lt;/code&gt; function allows us to apply the same function to everyvalue in an array and produce a new array containing the results. Each value in the original array maps to a corresponding value in the new array.&lt;/p&gt;

&lt;p&gt;For example, consider the following array of purple shapes. If we apply the mapping function 'make green' to it then every shape in the original array gets mapped to a green-colored shape in the new array.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oNT9bkuo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://scrimba.com/articles/content/images/2022/11/Array-Mapping.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oNT9bkuo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://scrimba.com/articles/content/images/2022/11/Array-Mapping.png" alt="" width="880" height="575"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In a similar way, applying the 'make love' function to the following array of shapes will return an array where every element in the original array has been mapped to a love heart of the same color:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--A1senlbb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://scrimba.com/articles/content/images/2022/11/Array-Mapping-1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--A1senlbb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://scrimba.com/articles/content/images/2022/11/Array-Mapping-1.png" alt="" width="880" height="575"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Array.map&lt;/code&gt; method works in the same way as a mathematical function. It iterates over the array that calls the method and returns a new array, with each value from the calling array mapped to a corresponding new value, based on a mapping function.&lt;/p&gt;

&lt;p&gt;For example, the following mapping function would double every number:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const double = n =&amp;gt; 2 * n
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The mapping function is provided as an argument to the &lt;code&gt;Array.map&lt;/code&gt;method. Functions that are provided as an argument are often referred to as callbacks. The fact that &lt;code&gt;Array.map&lt;/code&gt; accepts a function as an argument means that it is a higher order function, which is any function that accepts another function as an argument or returns a function.&lt;/p&gt;

&lt;p&gt;Another important point is that the &lt;code&gt;Array.map&lt;/code&gt; method doesn't mutate the original array that calls it. It returns a completely new array of new values and leaves the original array unchanged.&lt;/p&gt;

&lt;p&gt;This ability to map each item in an array to a new value without changing the underlying structure of the array means that JavaScript arrays are examples of a &lt;a href="https://en.wikipedia.org/wiki/Functor"&gt;functor&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Array.map examples
&lt;/h2&gt;

&lt;p&gt;Let's take a look at some examples of using the &lt;code&gt;Array.map&lt;/code&gt; method in JavaScript.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Mapping numbers&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;First of all, let's create an array of numbers that we can apply these mapping functions to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1, 2, 3, 4, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's define some mapping functions that can be used to map one value to another:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const increment = n =&amp;gt; n + 1
const double = n =&amp;gt; 2 * n
const square = n =&amp;gt; n * n
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we have three mapping functions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;increment&lt;/code&gt; returns the next number after the argument&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;double&lt;/code&gt; returns the argument multiplied by 2&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;square&lt;/code&gt; returns the argument multiplied by itself&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's have a go at using them:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers.map(increment)

// result [2,3,4,5,6]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, when the &lt;code&gt;increment&lt;/code&gt; mapping function is provided as an argument, the array that is returned has the same number of elements as the &lt;code&gt;numbers&lt;/code&gt; array, but each corresponding value has been incremented by one.&lt;/p&gt;

&lt;p&gt;We can also confirm that the &lt;code&gt;numbers&lt;/code&gt; array hasn't been changed by the operation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers

// result [1, 2, 3, 4, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we provide the &lt;code&gt;double&lt;/code&gt; mapping function as an argument, it will return an array where each value is twice as big as the corresponding value in the &lt;code&gt;numbers&lt;/code&gt; array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers.map(double)

// result [2, 4, 6, 8, 10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since the &lt;code&gt;Array.map&lt;/code&gt; method returns a new array, it's often helpful to assign the returned value to a variable. For example, we can provide the &lt;code&gt;square&lt;/code&gt; mapping function as an argument to the &lt;code&gt;numbers&lt;/code&gt;array, which will return a new array that correspond to the &lt;a href="https://en.wikipedia.org/wiki/Square_number"&gt;square numbers&lt;/a&gt;, so it makes sense to assign the return value to the variable &lt;code&gt;squareNumbers&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const squareNumbers = numbers.map(square)

// result [1, 4, 9, 16, 25]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we don't have a named mapping function that performs the operation we need, we can provide an anonymous function as an argument. The following example will subtract each value in the &lt;code&gt;numbers&lt;/code&gt; array from 10:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers.map(n =&amp;gt; 10 - n)

// result [9, 8, 7, 6, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can also chain mappings together and apply two functions to each value in the &lt;code&gt;numbers&lt;/code&gt; array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers.map(double).map(increment)

// result [3, 5, 7, 9, 11]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will double all the numbers and add one to them all. However, this is an example of just because you can do something, doesn't mean you should. If you want to double the numbers then add one, it would be much more efficient to write a new mapping function that does this instead of applying the &lt;a href="http://array.map/"&gt;&lt;code&gt;Array.map&lt;/code&gt;&lt;/a&gt; method twice. This is because every time you use the &lt;code&gt;Array.map&lt;/code&gt; method, you loop over the array, so applying it twice will result in two passes of the array. This isn't much of a problem when the array isn't very long, but in reality you may be dealing with huge sets of data and should try and limit the number of times you loop over the array.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Mapping strings&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;We can also use the &lt;code&gt;Array.map&lt;/code&gt; method to transform an array of strings. To demonstrate this, let's create an array called &lt;code&gt;words&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const words = ["hello","world"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And let's create a mapping function that accepts a string as an argument and returns that string written in reverse:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; const reverse = string =&amp;gt; [...string].reverse().join()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Providing the &lt;code&gt;reverse&lt;/code&gt; mapping function as an argument to &lt;code&gt;words.map&lt;/code&gt; will return a new array with each word written backwards:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;words.map(reverse)

// result ["olleH", "dlroW"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can also use built-in string methods by providing an anonymous function as a callback that calls the method we want on each string in the array. In the following example, we call the &lt;code&gt;toUpperCase&lt;/code&gt; string method on each word in the array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;words.map(word =&amp;gt; word.toUpperCase())

// result ["HELLO", "WORLD"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This returns a new array with each word written in capital letters.&lt;/p&gt;

&lt;p&gt;A common pattern when mapping over strings is to insert them into HTML tags. For example, we could wrap heading tags around the words using the following mapping function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const makeHeading = text =&amp;gt; &amp;lt;h1&amp;gt;${text}&amp;lt;/h1&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we provide the &lt;code&gt;makeHeading&lt;/code&gt; function as an argument to the mapping over the &lt;code&gt;words&lt;/code&gt; array, it will return an array of HTML:&lt;/p&gt;

&lt;p&gt;This HTML can then be inserted into a web page.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Mapping objects&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;We can also use &lt;code&gt;Array.map&lt;/code&gt; to extract information from a list of objects. For example, we could have a list of objects that describe different types of fruit, something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fruits = [
    { name: "Apple"
      price: 25
      emoji: "🍏"
    },
    { name: "Banana"
      price: 40
      emoji: "🍌"
    },
    { name: "Melon"
      price: 75
      emoji: "🍉"
    },
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first thing we can do is extract all the values of a specific property from each object. For example, if we only wanted to see the &lt;code&gt;emoji&lt;/code&gt;property, we could use the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fruits.map(fruit =&amp;gt; fruit.emoji)

// result  ["🍏","🍌","🍉"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This maps each object to a single value that corresponds to the &lt;code&gt;emoji&lt;/code&gt; property of each object.&lt;/p&gt;

&lt;p&gt;We can also map over an array of objects to create a string of HTML based on the object's values. The following code will create a list item based on each object in the &lt;code&gt;fruits&lt;/code&gt; array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fruitList = fruit.map(
    fruit =&amp;gt; `&amp;lt;li&amp;gt;${fruit.emoji} ${fruit.name}, ${fruit.price}c each&amp;lt;/li&amp;gt;`)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will return the following array of HTML:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;["&amp;lt;li&amp;gt;🍏 Apple, 25c each&amp;lt;/li&amp;gt;","&amp;lt;li&amp;gt;🍌 Banana, 40 each&amp;lt;/li&amp;gt;","&amp;lt;li&amp;gt;🍉 Melon, 75c each&amp;lt;/li&amp;gt;"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This example shows how you can take a load of data stored in an array of objects and use map to create an array of HTML. This is the foundation of using &lt;code&gt;Array.map&lt;/code&gt; to create JSX code that can be used in React components.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using map in React
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;Array.map&lt;/code&gt; function comes into its own when we need to insert a list of data from an array into a JSX component. Let's take a look at a simple example using this array of super heroes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const heroes = ["Superman", "Batman", "Wonder Woman"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can create a component that uses &lt;code&gt;Array.map&lt;/code&gt; to iterate over each super hero in the &lt;code&gt;heroes&lt;/code&gt; array and create a level-1 heading containing the name of each super hero:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Headings = () =&amp;gt; {
  const headings = heroes.map((hero, index)=&amp;gt;
    &amp;lt;h1 key={index}&amp;gt;{hero}&amp;lt;/h1&amp;gt;)
  return &amp;lt;header&amp;gt;{headings}&amp;lt;/header&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The return value of &lt;code&gt;Array.map&lt;/code&gt; is stored in the variable &lt;code&gt;headings&lt;/code&gt;. This can now be inserted as an expression into the return value of the the &lt;code&gt;Headings&lt;/code&gt; component. Each element in the &lt;code&gt;heroes&lt;/code&gt; array will then be rendered as a heading.&lt;/p&gt;

&lt;p&gt;You can see &lt;a href="https://codepen.io/daz4126/pen/xxzxRxG"&gt;this example on CodePen&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This example shows how easy it is to use &lt;code&gt;Array.map&lt;/code&gt; to display a list of data using a single line of code.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Using keys&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;An important point to remember when using &lt;code&gt;Array.map&lt;/code&gt; to create a list of items in React is that you must provide a &lt;code&gt;key&lt;/code&gt; prop. This is used by React in the background to keep track of the order of the items in the list. It becomes particularly important if the items in the list are likely to change order or if items are added or removed from the list.&lt;/p&gt;

&lt;p&gt;React uses a &lt;a href="https://reactjs.org/docs/faq-internals.html"&gt;virtual DOM&lt;/a&gt; to keep track of any changes that are made and keys are important in making sure that these changes are as rendered in the most efficient way possible.&lt;/p&gt;

&lt;p&gt;An easy way to create a &lt;code&gt;key&lt;/code&gt; prop is to use the index of the array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Headings = () =&amp;gt; {
    const headings = heroes.map((hero,index) =&amp;gt; &amp;lt;h1 key={index}&amp;gt;{hero}&amp;lt;/h1&amp;gt;)
    return &amp;lt;header&amp;gt;{headings}&amp;lt;/header&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is not best practice however, as the index of each element will change if the underlying data changes and won't help the virtual DOM keep track of any changes.&lt;/p&gt;

&lt;p&gt;Ideally each element needs to use a unique value as its &lt;code&gt;key&lt;/code&gt; prop. Thankfully most data provided by a database or API usually comes with unique IDs that we can use as the &lt;code&gt;key&lt;/code&gt; prop.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Lists of objects&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Let's finish off by looking at a more realistic example where you have an array of objects that have been pulled from a database or external API. For example, the following list of coding books:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const books = [
  { id: "B09123N2QN",
   title: "Learn To Code With JavaScript",
   author: "Darren Jones",
   price: 2260,
   pages: 425,
   cover: "https://m.media-amazon.com/images/I/412KSS+3fjL._SX260_.jpg",
   keywords: ["coding", "javascript", "beginner"]
 },
  { id: "B088P9Q6BB",
   title: "JavaScript: The Definitive Guide",
   author: "David Flanagan",
   price: 2399,
   pages: 708,
   cover: "https://m.media-amazon.com/images/I/51wijnc-Y8L._SX260_.jpg",
   keywords: ["rhino", "javascript", "mastery"]
 },
  { id: "B07C96Q217",
   title: "Eloquent JavaScript",
   author: "Marijn Haverbeke",
   price: 1994,
   pages: 474,
   cover: "https://m.media-amazon.com/images/I/51-5ZXYtcML.jpg",
   keywords: ["eloquent", "javascript", "modern"]
 },
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we wanted to display a list of books, showing the title and cover, we could create a Book component that returned the JSX we required:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Book = ({id,title,cover}) =&amp;gt;
  &amp;lt;li key={id}&amp;gt;
    &amp;lt;h2&amp;gt;{title}&amp;lt;/h2&amp;gt;
    &amp;lt;img alt={`cover of ${title}`} src={cover} /&amp;gt;
  &amp;lt;/li&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This takes the book object and uses destructuring in the parameter list to extract the &lt;code&gt;id&lt;/code&gt;, &lt;code&gt;title&lt;/code&gt; and &lt;code&gt;cover&lt;/code&gt; properties. These are then used to return a list item that displays the title as a level-1 heading and the cover of the book as an image.&lt;/p&gt;

&lt;p&gt;Now we can create a &lt;code&gt;BookList&lt;/code&gt; component that uses &lt;code&gt;Array.map&lt;/code&gt; to create a list of books by using the &lt;code&gt;Book&lt;/code&gt; function as the mapping function that is provided as an argument:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const BookList = () =&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;Books&amp;lt;/h1&amp;gt;
      &amp;lt;ul&amp;gt;
        {books.map(Book)}
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;BookList&lt;/code&gt; component creates a container &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt; and heading and then provides the &lt;code&gt;&amp;lt;ul&amp;gt;&lt;/code&gt; elements to contain the list of books. We then use &lt;code&gt;Array.map&lt;/code&gt; to loop over the list of books and insert a &lt;code&gt;Book&lt;/code&gt; component in place of each value in the &lt;code&gt;books&lt;/code&gt;array.&lt;/p&gt;

&lt;p&gt;You can see &lt;a href="https://codepen.io/daz4126/pen/QWxLYBX"&gt;this example on CodePen&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Limiting the list&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This is fine in this case as the &lt;code&gt;books&lt;/code&gt; array only contains 3 books, but in reality an API might return hundreds of book objects, so how can you limit the number of books that are displayed using the &lt;code&gt;map&lt;/code&gt;method? It's actually quite straightforward, you can just use the &lt;code&gt;slice&lt;/code&gt; method to cut the array down to size, for example, if you only want to display the first 2 books, you can update the &lt;code&gt;BookList&lt;/code&gt;component to the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const BookList = ({n}) =&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;Books&amp;lt;/h1&amp;gt;
      &amp;lt;ul&amp;gt;
        {books.slice(0,n).map(Book)}
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's much better to slice the array before applying the map function as avoids the whole of the &lt;code&gt;books&lt;/code&gt; array being iterated over.&lt;/p&gt;

&lt;p&gt;We can make the &lt;code&gt;BookList&lt;/code&gt; component a bit more general by providing the number of books to display in the list as a prop, to the component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const BookList = ({n}) =&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;Books&amp;lt;/h1&amp;gt;
      &amp;lt;ul&amp;gt;
        {books.slice(0,n).map(Book)}
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can choose the value of &lt;code&gt;n&lt;/code&gt; that will determine the number of books displayed in the list. This is called when we render the &lt;code&gt;BookList&lt;/code&gt; component, like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ReactDOM.render(&amp;lt;BookList n={2} /&amp;gt;, document.getElementById("root"))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;Displaying data in a table&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The last example used &lt;code&gt;map&lt;/code&gt; to create an unordered list of items, which is an obvious way to present data from an array, but we can also use it to iterate over data and present it in other ways as well, for example we could create a table to display all the information about our &lt;code&gt;books&lt;/code&gt; array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const BookRow = ({id,title,author,price,pages}) =&amp;gt;
  &amp;lt;tr key={id}&amp;gt;
    &amp;lt;td&amp;gt;{title}&amp;lt;/td&amp;gt;
    &amp;lt;td&amp;gt;{author}&amp;lt;/td&amp;gt;
    &amp;lt;td&amp;gt;{pages}&amp;lt;/td&amp;gt;
    &amp;lt;td&amp;gt;£{price/100}&amp;lt;/td&amp;gt;
  &amp;lt;/tr&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we can create the actual table to hold all these rows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const BookTable = () =&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;Books&amp;lt;/h1&amp;gt;
      &amp;lt;table&amp;gt;
        &amp;lt;thead&amp;gt;
          &amp;lt;th&amp;gt;Title&amp;lt;/th&amp;gt;
          &amp;lt;th&amp;gt;Author&amp;lt;/th&amp;gt;
          &amp;lt;th&amp;gt;Number of Pages&amp;lt;/th&amp;gt;
          &amp;lt;th&amp;gt;Price&amp;lt;/th&amp;gt;
        &amp;lt;/thead&amp;gt;
        &amp;lt;tbody&amp;gt;
        {books.map(BookRow)}
        &amp;lt;/tbody&amp;gt;
      &amp;lt;/table&amp;gt;
    &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This sets up the table and table headings and then after the heading row, we use &lt;code&gt;Array.map&lt;/code&gt; to map over each book in the &lt;code&gt;books&lt;/code&gt;array and pass it to the &lt;code&gt;BookRow&lt;/code&gt;component. This has the effect of creating a new row for every element in the &lt;code&gt;books&lt;/code&gt;array.&lt;/p&gt;

&lt;p&gt;You can see &lt;a href="https://codepen.io/daz4126/pen/BaVBbXz"&gt;this example on CodePen&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Creating a nested list&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Sometimes an array will contain objects that also contain arrays as properties. These might need to be mapped over as well in order to display them using JSX. In this case we can create a nested map statement.&lt;/p&gt;

&lt;p&gt;For example, our &lt;code&gt;books&lt;/code&gt; array contains a property called &lt;code&gt;keywords&lt;/code&gt; which is an array of key words about each book. What if we wanted to display the title of each book with its keywords listed underneath like tags?&lt;/p&gt;

&lt;p&gt;First of all we could create &lt;code&gt;Tag&lt;/code&gt; component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Tag = word =&amp;gt;
  &amp;lt;div className="tag"&amp;gt;{word}&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we create a &lt;code&gt;Book&lt;/code&gt; component, similar to the one we used earlier:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Book = ({id,title,keywords}) =&amp;gt;
  &amp;lt;li key={id}&amp;gt;
    &amp;lt;h2&amp;gt;{title}&amp;lt;/h2&amp;gt;
  &amp;lt;div&amp;gt;{keywords.map(Tag)}&amp;lt;/div&amp;gt;
  &amp;lt;/li&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This time we use &lt;code&gt;Array.map&lt;/code&gt; again map over the keywords array, which will insert a new &lt;code&gt;Tag&lt;/code&gt; component inside a &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt; element for each keyword in the array.&lt;/p&gt;

&lt;p&gt;Last of all we need a &lt;code&gt;BookList&lt;/code&gt; component that will map over the &lt;code&gt;books&lt;/code&gt; array and create a list of &lt;code&gt;Book&lt;/code&gt; components (this component is exactly the same as the one we used earlier):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const BookList = ({n}) =&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;Books&amp;lt;/h1&amp;gt;
      &amp;lt;ul&amp;gt;
        {books.slice(0,n).map(Book)}
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can see an &lt;a href="https://codepen.io/daz4126/pen/jOKNRGz"&gt;example on CodePen&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We can see here that the &lt;code&gt;Array.map&lt;/code&gt; in the &lt;code&gt;BookList&lt;/code&gt;component iterates over the &lt;code&gt;books&lt;/code&gt; array and then the &lt;code&gt;Array.map&lt;/code&gt; in the &lt;code&gt;Book&lt;/code&gt; component iterates over every element in the keywords property of every element in the  &lt;code&gt;books&lt;/code&gt; array.&lt;/p&gt;

&lt;h2&gt;
  
  
  The verdict
&lt;/h2&gt;

&lt;p&gt;The &lt;a href="http://array.map/"&gt;Array.map&lt;/a&gt; method is a powerful higher-order function that lets you transform all the values in an array using a mapping function. This is especially useful for inserting a list of data into a React app, since you can't use &lt;code&gt;for&lt;/code&gt; loops. It lets you replace elements in an array with a component based on the data in the array. When dealing with data that will change, it is important that you provide a unique &lt;code&gt;key&lt;/code&gt;prop for each component in the list. Once you've got the hang of using the Array.mapmethod to display lists of data into React, you'll wonder how you ever managed without it!&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>react</category>
    </item>
    <item>
      <title>How to use Array.filter to narrow down a list in React</title>
      <dc:creator>DAZ</dc:creator>
      <pubDate>Sat, 17 Dec 2022 15:59:18 +0000</pubDate>
      <link>https://dev.to/daz4126/how-to-use-arrayfilter-to-narrow-down-a-list-in-react-160i</link>
      <guid>https://dev.to/daz4126/how-to-use-arrayfilter-to-narrow-down-a-list-in-react-160i</guid>
      <description>&lt;p&gt;How do you filter lists of data based on some user input? This is easily done using the &lt;code&gt;Array.filter&lt;/code&gt; method!&lt;/p&gt;

&lt;h2&gt;
  
  
  How Does &lt;code&gt;Array.filter&lt;/code&gt; Work? 🤔
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;Array.filter&lt;/code&gt; method takes an array of items and returns a completely new array that only contains the elements from the original array that match certain conditions. The original array is not changed at all, making this a non-destructive operation.&lt;/p&gt;

&lt;p&gt;Now we're going to look at the most important concept in this post: The conditions are provided by a predicate functionwhich might sound complicated, but is really just a fancy name for a function that returns either &lt;code&gt;true&lt;/code&gt; or &lt;code&gt;false&lt;/code&gt; based on certain conditions.&lt;/p&gt;

&lt;p&gt;A predicate function is is provided as an argument to the &lt;code&gt;Array.filter&lt;/code&gt; method.. If it returns &lt;code&gt;true&lt;/code&gt; then the element will be in the returned array. If it returns &lt;code&gt;false&lt;/code&gt; then the element will not be included in the returned array.&lt;/p&gt;

&lt;p&gt;For example applying the predicate function &lt;code&gt;isPurple&lt;/code&gt; to this array of shapes will result in a new array containing only the purple shapes from the original array:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--o1QKGEYd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://scrimba.com/articles/content/images/2022/11/array-filter-example-1-1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--o1QKGEYd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://scrimba.com/articles/content/images/2022/11/array-filter-example-1-1.png" alt="" width="880" height="575"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the next example, applying the predicate function &lt;code&gt;isRound&lt;/code&gt; to the array of shapes will result in a new array containing all the circles that were in the original array:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RKYQ9Pea--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://scrimba.com/articles/content/images/2022/11/array-filter-example-2-1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RKYQ9Pea--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://scrimba.com/articles/content/images/2022/11/array-filter-example-2-1.png" alt="" width="880" height="575"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's have a quick look at some code that will filter the following array of numbers:&lt;/p&gt;

&lt;h2&gt;
  
  
  Simplest possible filter example
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First of all, we need a predicate function. The following &lt;code&gt;isEven&lt;/code&gt; function will return true if the number provided as an argument is even and false otherwise:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const isEven = number =&amp;gt; number % 2 === 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you know what &lt;code&gt;isEven&lt;/code&gt; does, can you predict what the following code will return?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers.filter(isEven)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you guessed that only the even numbers in the &lt;code&gt;numbers&lt;/code&gt; array will be returned then congratulations, you were absolutely right:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[2, 4, 6, 8, 10]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's look at a more real-world example in React that takes an array of exam results and filters them to find out which marks got a distinction and which failed.&lt;/p&gt;

&lt;h2&gt;
  
  
  Filter list in React
&lt;/h2&gt;

&lt;p&gt;First of all, we need to create a variable to store the exam results (these are just a list of random marks out of 100, feel free to make your own up):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const testResults = [56, 68, 100, 75, 85, 76, 45, 83, 38, 45, 67]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we need to create predicate functions for filtering out the marks that failed the exam and the marks that get a distinction. Getting less than 40% is a fail and getting 85% or more is a distinction. Each predicate function accepts the mark as the only parameter and returns the Boolean result of checking if the mark is less than 40 or greater than or equal to 85:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fail = mark =&amp;gt; mark &amp;lt; 40
const distinction = mark =&amp;gt; mark &amp;gt;= 85

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To display a list of all the marks we will use the following &lt;code&gt;App&lt;/code&gt; component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const App = ({results}) =&amp;gt;
  &amp;lt;div&amp;gt;
    &amp;lt;h1&amp;gt;Distinctions&amp;lt;/h1&amp;gt;
    &amp;lt;div&amp;gt;{results.filter(distinction).join(",")}&amp;lt;/div&amp;gt;
    &amp;lt;h1&amp;gt;Fails&amp;lt;/h1&amp;gt;
    &amp;lt;div&amp;gt;{results.filter(fail).join(",")}&amp;lt;/div&amp;gt;
  &amp;lt;/div&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The important lines here are where we use &lt;code&gt;Array.filter&lt;/code&gt; to only display the marks that have achieved the distinction and fail marks:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div&amp;gt;{results.filter(distinction).join(",")}&amp;lt;/div&amp;gt;
&amp;lt;div&amp;gt;{results.filter(fail).join(",")}&amp;lt;/div&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, it's as simple as calling the &lt;code&gt;filter&lt;/code&gt; method with the relevant predicate function to filter the &lt;code&gt;results&lt;/code&gt; array and leave just the results we want. We also use the &lt;code&gt;join&lt;/code&gt; method to display a string with each result joined by a comma. In the later examples we will use &lt;code&gt;[Array.map](&amp;lt;http://Array.map&amp;gt;)&lt;/code&gt; to add some JSX to each element.&lt;/p&gt;

&lt;p&gt;You can see this example on &lt;a href="https://codepen.io/daz4126/pen/YzvyrEX"&gt;CodePen&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Note that this technique should only be used if you are filtering a list of data dynamically based on user input, otherwise you should really apply the filter at the point when you actually get the data from the database or API as this will save you having to fetch large amounts of data that you're not actually going to use.&lt;/p&gt;

&lt;h2&gt;
  
  
  Filtering With Hooks
&lt;/h2&gt;

&lt;p&gt;Next we're going to expand on the previous example by using React's hooks to add some buttons to filter the test results.&lt;/p&gt;

&lt;p&gt;This example is quite similar to the last one, but with a few changes that we'll discuss:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const testResults = [56, 68, 100, 75, 85, 76, 45, 83, 38, 45, 67]

const App = ({results}) =&amp;gt; {
  const [level, setLevel] = useState("distinction")
  const checkResults = mark =&amp;gt; level === "distinction" ? mark &amp;gt; 85 : mark &amp;lt; 40
  return &amp;lt;div&amp;gt;
    &amp;lt;button onClick={e =&amp;gt; setLevel("distinction")}&amp;gt;Distinctions&amp;lt;/button&amp;gt;
    &amp;lt;button onClick={e =&amp;gt; setLevel("fail")}&amp;gt;Fails&amp;lt;/button&amp;gt;
    &amp;lt;h1&amp;gt;Test Marks&amp;lt;/h1&amp;gt;
    &amp;lt;div&amp;gt;{results.join(",")}&amp;lt;/div&amp;gt;
    &amp;lt;h1&amp;gt;{level === "distinction" ? "Distinctions" : "Fails"}&amp;lt;/h1&amp;gt;
    &amp;lt;div&amp;gt;{results.filter(checkResults).join(",")}&amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
}

ReactDOM.render(&amp;lt;App results={testResults} /&amp;gt;, document.getElementById("root"))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First of all, we use the &lt;code&gt;useState&lt;/code&gt; hook to set a variable called &lt;code&gt;level&lt;/code&gt; and give it a default value of "distinction":&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [level, setLevel] = useState("distinction")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will be used to track whether or not we want look at the distinction or fail results.&lt;/p&gt;

&lt;p&gt;Next we create the predicate function that we'll use to filter the results:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const checkResults = mark =&amp;gt; level === "distinction" ? mark &amp;gt; 85 : mark &amp;lt; 40

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a combination of the two predicate functions we used last time. We use a ternary operator to check if the &lt;code&gt;leve&lt;/code&gt;l is set to "distinction" and if it is, we filter marks that are over 85, if not then we must be looking for "fail" marks so filter marks below 40.&lt;/p&gt;

&lt;p&gt;In the JSX that is returned, we need to add a couple of buttons&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button onClick={e =&amp;gt; setLevel("distinction")}&amp;gt;Distinctions&amp;lt;/button&amp;gt;
&amp;lt;button onClick={e =&amp;gt; setLevel("fail")}&amp;gt;Fails&amp;lt;/button&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These both use the &lt;code&gt;setLevel&lt;/code&gt; method to update the value of &lt;code&gt;level&lt;/code&gt; to "distinction" or "fail" depending on which button is pressed.&lt;/p&gt;

&lt;p&gt;Next we just display all the results in a comma-separated list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;h1&amp;gt;Test Marks&amp;lt;/h1&amp;gt;
&amp;lt;div&amp;gt;{results.join(",")}&amp;lt;/div&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we display the filtered results and use a ternary operator to create a heading that says "Distinctions" or "Fails" based on the value of &lt;code&gt;level&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;h1&amp;gt;{level === "distinction" ? "Distinctions" : "Fails"}&amp;lt;/h1&amp;gt;
&amp;lt;div&amp;gt;{results.filter(checkResults).join(",")}&amp;lt;/div&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can see this on &lt;a href="https://codepen.io/daz4126/pen/LYrezKJ"&gt;CodePen&lt;/a&gt;:&lt;/p&gt;

&lt;h2&gt;
  
  
  Filtering Strings As You Type
&lt;/h2&gt;

&lt;p&gt;Now let's take a look at how you might filter strings. A common feature of large lists of data is to allow users to search the list and filter it as they type. Let's use &lt;code&gt;Array.filter&lt;/code&gt; to implement this functionality.&lt;/p&gt;

&lt;p&gt;The code to do this can be seen below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const App = () =&amp;gt; {
  const languages = ["JavaScript","Python","C","C++","C#","Swift","Java","Ruby","Haskell"]
  const [searchString, setSearchString] = useState()
  const startsWith = str =&amp;gt; word =&amp;gt; str ? word.slice(0,str.length).toLowerCase() === str.toLowerCase() : true

  return &amp;lt;div&amp;gt;
           &amp;lt;input onChange={e =&amp;gt; setSearchString(e.target.value)} /&amp;gt;
           &amp;lt;ul&amp;gt;
            {languages.filter(startsWith(searchString)).map(lang =&amp;gt; &amp;lt;li&amp;gt;{lang}&amp;lt;/li&amp;gt;)}
           &amp;lt;/ul&amp;gt;
         &amp;lt;/div&amp;gt;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's break down how this works.&lt;/p&gt;

&lt;p&gt;First of all, we create a list of programming languages that we'll be displaying and filtering (feel free to add any more!):&lt;/p&gt;

&lt;p&gt;Next we use the &lt;code&gt;useState&lt;/code&gt; hook to store a variable called &lt;code&gt;searchString&lt;/code&gt;. This will be the string that the user enters and is used to filter the languages by only displaying languages include that string::&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [searchString, setSearchString] = useState()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we need a predicate function to do the filtering:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const contains = str =&amp;gt; word =&amp;gt; str ? word.toLowerCase().includes(str.toLowerCase()) : true

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we use the includes method to check if the &lt;code&gt;searchString&lt;/code&gt; is included in each word. We convert both strings to lowercase so that we don't need to worry about the case matching. If the &lt;code&gt;searchString&lt;/code&gt; is in included in the string then we'll keep the string in the new array, if not, it will be filtered out. If there isn't a search string, then this predicate function will just return true, meaning that every element in the original array will remain.&lt;/p&gt;

&lt;p&gt;Last of all, we just need to return the JSX for the view:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return &amp;lt;div&amp;gt;
           &amp;lt;input onChange={e =&amp;gt; setSearchString(e.target.value)} /&amp;gt;
           &amp;lt;div&amp;gt;
            {languages.filter(contains(searchString)).join(",")}
           &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we use an input element with an &lt;code&gt;onChange&lt;/code&gt; event listener that will fire every time anything is entered into the input box. When this happens, the value of the &lt;code&gt;searchString&lt;/code&gt; is updated to whatever is inside the &lt;code&gt;input&lt;/code&gt; element and this is passed to the &lt;code&gt;contains&lt;/code&gt; function to create a predicate function that will filter the array.&lt;/p&gt;

&lt;p&gt;The example can be seen on &lt;a href="https://codepen.io/daz4126/pen/yLEOPjQ"&gt;CodePen&lt;/a&gt;, have a play around with it to see how it works!&lt;/p&gt;

&lt;h2&gt;
  
  
  Filtering Objects
&lt;/h2&gt;

&lt;p&gt;As we know, most data that we'll end up using will be stored as objects. These can be filtered just as easily as numbers and strings using predicate functions. Let's create an array of objects to filter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const people = [{
        emoji: "🤶",
        hat: true,
        glasses: true
    },
    {
        emoji: "🤴",
        hat: true,
        glasses: false
    },
    {
        emoji: "👩‍🍳",
        hat: true,
        glasses: false
    },
    {
        emoji: "👷‍♀️",
        hat: true,
        glasses: false
    },
    {
        emoji: "👴",
        hat: false,
        glasses: true
    },
    {
        emoji: "👵",
        hat: false,
        glasses: true
    },
    {
        emoji: "👩‍🔬",
        hat: false,
        glasses: true
    },
    {
        emoji: "👦",
        hat: false,
        glasses: false
    },
    {
        emoji: "👩‍🔧",
        hat: false,
        glasses: false
    },
    {
        emoji: "👩‍🦰",
        hat: false,
        glasses: false
    }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This array contains a number of objects that contain an &lt;code&gt;emoji&lt;/code&gt; property and two other Boolean properties called &lt;code&gt;hat&lt;/code&gt; and &lt;code&gt;glasses&lt;/code&gt; that describe whether or not the emoji wears a hat and glasses respectively.&lt;/p&gt;

&lt;p&gt;First of all, we'll add a filter to display only the emojis that are wearing hats.&lt;/p&gt;

&lt;p&gt;We'll use the &lt;code&gt;setState&lt;/code&gt; hook to do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [hat, setHat] = useState(true)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For example, if &lt;code&gt;hat&lt;/code&gt; is true, then we only want to display the emojis that are wearing a hat.&lt;/p&gt;

&lt;p&gt;In order to allow the user to change the state, we'll add a button that changes the value of the &lt;code&gt;hat&lt;/code&gt; variable:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button onClick={e =&amp;gt; setHat(!hat)} className={hat ? "active" : null}&amp;gt;Hat&amp;lt;/button&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Clicking on these buttons will flip the Boolean value of  &lt;code&gt;hat&lt;/code&gt;, so if it is &lt;code&gt;true&lt;/code&gt; it will be set to &lt;code&gt;false&lt;/code&gt; and vice versa.&lt;/p&gt;

&lt;p&gt;Last of all, we just need to apply &lt;code&gt;Array.filter&lt;/code&gt; in order to filter based on the value of  &lt;code&gt;hat&lt;/code&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;ul&amp;gt;
  {people.filter(person =&amp;gt; person.hat === hat).map(person =&amp;gt; &amp;lt;li&amp;gt;{person.emoji}&amp;lt;/li&amp;gt;)}
&amp;lt;/ul&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that this example also uses &lt;code&gt;[Array.map](&amp;lt;http://Array.map&amp;gt;)&lt;/code&gt; to make sure that we only display the "emoji" property of the object as an HTML list-item. You can &lt;a href="https://scrimba.com/articles/react-list-array-with-map-function/"&gt;read more about how to do this here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Clicking on the button will alternate the display between showing a filtered list of emojis wearing hats and not wearing hats. &lt;/p&gt;

&lt;p&gt;You can see this example on &lt;a href="https://codepen.io/daz4126/pen/rNKppaP"&gt;CodePen&lt;/a&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  Multiple Filters
&lt;/h1&gt;

&lt;p&gt;For our last example, we're going to expand on the previous example to demonstrate how to filter multiple items at once. We'll do this by adding a second button that will add a filter based on whether the emojis are wearing glasses or not. This was another Boolean property that was in each object.&lt;/p&gt;

&lt;p&gt;First of all we need to use the &lt;code&gt;setState&lt;/code&gt; hook to add another variable to track the state of whether the emoji has glasses or not. This follows the same pattern we used earlier for whether or not they were wearing a hat:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [glasses, setGlasses] = useState(true)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we need to add a button that will toggle the Boolean value of &lt;code&gt;glasses&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button onClick={e =&amp;gt; setGlasses(!glasses)} className={glasses ? "active" : null}&amp;gt;Glasses&amp;lt;/button&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we chain two filters one after the other to first check if the emoji is wearing a hat and then to check if they are wearing glasses or not:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;ul&amp;gt;
   {people.filter(person =&amp;gt; person.hat === hat).filter(person =&amp;gt; person.glasses === glasses).map(person =&amp;gt; &amp;lt;li&amp;gt;{person.emoji}&amp;lt;/li&amp;gt;)}
&amp;lt;/ul&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This filter starts and ends in the same way as earlier, but we have chained the following filter into the middle of the expression:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;filter(person =&amp;gt; person.glasses === glasses)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This means that first of all we will filter the list of objects based on the value of  &lt;code&gt;hat&lt;/code&gt;then we filter this new list based on the value of &lt;code&gt;glasses&lt;/code&gt;. The result is a list that matches both the states of the &lt;code&gt;hat&lt;/code&gt; and &lt;code&gt;glasses&lt;/code&gt; variables.&lt;/p&gt;

&lt;p&gt;This process of chaining multiple filters together works - if you make &lt;code&gt;hat&lt;/code&gt; and &lt;code&gt;glasses&lt;/code&gt; both true, then you will only see any emojis that are wearing a hat and glasses. This method can become inefficient however, especially with large amounts of data and even more Boolean conditions. The reason for this is that the original list needs to be iterated over for every &lt;code&gt;filter&lt;/code&gt; method. This means that you might have to go through a large list of objects multiple times, which could become inefficient and slow things down.&lt;/p&gt;

&lt;p&gt;A much better way to achieve the same result is to use a single &lt;code&gt;filter&lt;/code&gt; with the logical AND operator, &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt;. This will apply multiple predicates in a single filter. The example above can be rewritten more efficiently in the following way:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;ul&amp;gt;
  {people.filter(person =&amp;gt; person.hat === hat &amp;amp;&amp;amp; person.glasses === glasses).map(person =&amp;gt; &amp;lt;li&amp;gt;{person.emoji}&amp;lt;/li&amp;gt;)}
&amp;lt;/ul&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will still work in the same way, but only pass over the original array once to filter and then one more time to map each object to a string of HTML - much more efficient!&lt;/p&gt;

&lt;p&gt;You can see this on &lt;a href="https://codepen.io/daz4126/pen/zYaqLaV"&gt;CodePen&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Verdict
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;Array.filter&lt;/code&gt; method can be used to filter values in a list based on a given rule. This lets you filter data dynamically based on user input. In this post, we've looked at the different ways to use this method effectively with numbers, strings and objects as well as how to apply multiple filters all at once. I hope you've found this useful and can start using filters in your code today!&lt;/p&gt;

</description>
      <category>react</category>
      <category>beginners</category>
      <category>arrays</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
