<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jess Sommerville on Medium]]></title>
        <description><![CDATA[Stories by Jess Sommerville on Medium]]></description>
        <link>https://medium.com/@jesscsommer?source=rss-8ca2c24d37b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mkUBoVSHTC4Q3ZuU.jpg</url>
            <title>Stories by Jess Sommerville on Medium</title>
            <link>https://medium.com/@jesscsommer?source=rss-8ca2c24d37b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:28:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jesscsommer/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to serialize and validate your data with Marshmallow]]></title>
            <link>https://medium.com/@jesscsommer/how-to-serialize-and-validate-your-data-with-marshmallow-a815b2276a?source=rss-8ca2c24d37b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a815b2276a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-beginner]]></category>
            <category><![CDATA[flask-sqlalchemy]]></category>
            <category><![CDATA[marshmallow]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Jess Sommerville]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 00:16:40 GMT</pubDate>
            <atom:updated>2023-07-21T18:43:23.352Z</atom:updated>
            <content:encoded><![CDATA[<p>It turns out Lucky Charms and data serialization share their best ingredient: marshmallows. If you are building a Flask backend, then the <a href="https://marshmallow.readthedocs.io/en/stable/">Marshmallow library</a> can help you smoothly package your data for its API responses, as well as validate any new information prior to saving it to your database.</p><p>In this post, we’ll walk through how to set up schema for nested and non-nested fields, validate incoming data, and troubleshoot common errors. We’ll focus specifically on Marshmallow as it works with Flask-SQLAlchemy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*QYPXtYgma09QJT2T" /><figcaption><em>1 pts Marshmallow, 3 pts Flask API</em></figcaption></figure><h3><em>Serialization</em></h3><p>But first things first, what is <a href="https://hazelcast.com/glossary/serialization/">serialization</a> anyways?</p><blockquote>Serialization is the process by which you translate a data structure into another format in order to share or save the data.</blockquote><p>One example of this, and what we will focus on in our later walkthroughs, is when you take an instance of a Python class and convert it to JSON.</p><p>The process also works in reverse, this time known as <strong>deserialization, </strong>e.g.<strong> </strong>when you load JSON data into an instance of a Python class.</p><h3><em>Schema</em></h3><p>We serialize our data by defining <strong>schema, </strong>or rules for how each data field on a certain model should be represented. You may have heard of this in the context of <strong>database schema, </strong>where you outline the architecture of your database itself (tables, columns, relationships, etc).</p><p>The<strong> serialization schema</strong> has a similar intention — outline rules for a table or model — except now we are focusing solely on data representation, rather than data storage. We might save four columns for a table to our database, but choose only to display one or two once serialized.</p><h3><em>Defining Marshmallow Schema</em></h3><p>Let’s say we have three models: Users, Reviews, and Books.</p><ul><li>A user has many reviews.</li><li>A review has one user and one book.</li><li>A book has many reviews.</li></ul><p>We will not define these models in real-time, but there is a good reference for how you could get started <a href="https://rest-apis-flask.teclado.com/docs/sql_storage_sqlalchemy/create_simple_sqlalchemy_model/">here</a>.</p><p>Before we begin, double-check that you have installed Marshmallow and Flask-Marshmallow successfully and configured it for your Flask application.</p><pre># import Marshmallow and fields for initial setup<br>from flask_marshmallow import Marshmallow<br>from marshmallow import fields <br><br># set up Marshmallow for your particular Flask app <br>app = Flask(__name__)<br>ma = Marshmallow(app)</pre><p>Now we’ll dive in to creating schema for our Reviews model. To do so, we will create a new Python class that inherits from Marshmallow. Each schema class will include a <a href="https://marshmallow.readthedocs.io/en/stable/marshmallow.schema.html#marshmallow.schema.Schema.Meta">Meta sub-class</a> where we set our initial settings, prior to creating our field-by-field serialization rules.</p><pre># the schema class inherits from Marshmallow SQL Alchemy Schema<br>class ReviewSchema(ma.SQLAlchemySchema):<br>    # define schema settings in Meta subclass<br>    class Meta():<br>        # set your model equal to your defined model in another file<br>        # you may need to import the model to this file <br>        model = Review<br>        # allow deserialization to instances of the above model <br>        load_instance = True<br>        # choose which fields to serialize for reviews by default <br>        fields = (&quot;id&quot;, &quot;rating&quot;, &quot;comment&quot;, &quot;book&quot;, &quot;user&quot;)<br><br>    # define the expected data type for non-nested fields<br>    rating = fields.Float(required=True)<br>    comment = fields.String(required=True) <br>    # for nested fields, include the relevant schema for that model <br>    # customize the default schema<br>    # in this case by limiting what you get back with &quot;only&quot;<br>    book = fields.Nested(BookSchema, only=(&quot;id&quot;, &quot;title&quot;))<br>    user = fields.Nested(UserSchema, only=(&quot;id&quot;, &quot;username&quot;))</pre><p>In our Meta sub-class, we connect our Review model to its corresponding schema. We name id, rating, comment, book and user as the fields we want to display when listing our reviews.</p><p>Outside the Meta sub-class, but within our ReviewSchema, we can list each displayed field and add additional requirements. Immediately following fields , we define its expected data type, float, string, or Nested , then open up a set of parentheses. There required=True is an example of a quick validation we could require when loading new instances of the Review class. In other words, a rating and comment are required to create a new review.</p><p>For nested fields, we start by referencing the corresponding schema for that model. Since the book field represents our separate Book model, we include BookSchema as its counterpart. Marshmallow offers us a variety of options to then customize this further.</p><p>When we are serializing reviews, we likely don’t need all the information our database has about each book, e.g. author, description, publication date. Instead we just want to see at a glance which book was reviewed and by whom. We can use only to limit the fields displayed for book and user to a couple each. Note: only expects a tuple of strings. If you were to only display one field, the required syntax would be only=(&quot;id&quot;,) .</p><p>Once we define our schema, it’s time to test it out and actually display our data. To do this, we instantiate an instance of our schema class, then call Marshmallow’s .dump() method to serialize.</p><pre># instantiate an instance of our review schema class<br># many=True because we want to serialize a collection of reviews <br>reviews_schema = ReviewSchema(many=True)<br><br># deserialize reviews according to the schema defined above<br># where reviews is a variable for the rows we want to return from the db<br>reviews_schema.dump(reviews) </pre><p>The serialized reviews would then appear as follows:</p><pre>## /reviews<br><br>[<br>     {<br>        &quot;id&quot;: 1,<br>        &quot;rating&quot;: 3.0,<br>        &quot;comment&quot;: &quot;Comment text&quot;,<br>        &quot;book&quot;: {<br>            &quot;id&quot;: 1,<br>            &quot;title&quot;: &quot;The Poppy War&quot;<br>        },<br>        &quot;user&quot;: {<br>            &quot;id&quot;: 1,<br>            &quot;username&quot;: &quot;user123&quot;<br>        }<br>    },<br>    {<br>        &quot;id&quot;: 2,<br>        &quot;rating&quot;: 4.5,<br>        &quot;comment&quot;: &quot;Comment text&quot;,<br>        &quot;book&quot;: {<br>            &quot;id&quot;: 2,<br>            &quot;title&quot;: &quot;The Dragon Republic&quot;<br>        },<br>        &quot;user&quot;: {<br>            &quot;id&quot;: 5,<br>            &quot;username&quot;: &quot;user567&quot;<br>        }<br>    }<br>]</pre><p>Looking good! We can quickly view each review’s rating and comment, along with some cursory information about the connected book and user.</p><p>If you recall, a review has one book and one user, but a book has many reviews. When we serialize our books, we probably want a lot more information about each title and a lot less about each review. That’s where our BookSchema comes in.</p><pre>class BookSchema(ma.SQLAlchemySchema):<br>  # similar initial subclass setup to Reviews <br>    class Meta():<br>        model = Book<br>        load_instance = True<br>        # define book-specific fields, plus reviews<br>        fields = (&quot;id&quot;, &quot;title&quot;, &quot;genre&quot;, &quot;page_count&quot;, &quot;reviews&quot;)<br><br>  # specify that reviews should only include id and rating <br>  # important: many=True accounts for a book having many reviews<br>  reviews = fields.Nested(&quot;ReviewSchema&quot;, only=(&quot;id&quot;, &quot;rating&quot;), many=True)</pre><p>Let’s focus in on that nested reviews field. If we hadn’t narrowed in what fields of the review to include, it would have defaulted fully to the ReviewSchema and also included additional information — notably, information about the book itself. This is not only redundant, because all our reviews are about book 1 when serializing book 1, but also creates a loop. If book serializes reviews which serializes book which serializes reviews … you see the problem ♾️</p><p>You could resolve this by adding exclude=(&quot;book&quot;,) to avoid doubly displaying the relationship. Here we only want some cursory information about each review, so we opt for only instead.</p><p>An important new addition is the many=True . Since we’ll have many reviews per book, we have to let our schema know in order for the nested data to display appropriately.</p><p>If we dump our books as we did with reviews above, the books will appear as follows:</p><pre>## /books<br><br>[<br>    {<br>        &quot;id&quot;: 1,<br>        &quot;genre&quot;: &quot;Fantasy&quot;,<br>        &quot;title&quot;: &quot;The Poppy War&quot;,<br>        &quot;page_count&quot;: 544,<br>        &quot;reviews&quot;: [<br>            {<br>                &quot;id&quot;: 1,<br>                &quot;rating&quot;: 3.0<br>            },<br>            {<br>                &quot;id&quot;: 3,<br>                &quot;rating&quot;: 2.5<br>            }<br>        ]<br>    },<br>    {<br>        &quot;id&quot;: 2,<br>        &quot;genre&quot;: &quot;Fantasy&quot;,<br>        &quot;title&quot;: &quot;The Dragon Republic&quot;,  <br>        &quot;page_count&quot;: 672,<br>        &quot;reviews&quot;: [<br>            {<br>                &quot;id&quot;: 2,<br>                &quot;rating&quot;: 4.5<br>            },<br>            {<br>                &quot;id&quot;: 4,<br>                &quot;rating&quot;: 3.0<br>            }<br>        ]<br>    }<br>]</pre><p>Here we can check out what that reviews-books relationship could look like from the other side, or how the same exact row in the database could be serialized in different ways.</p><h3><em>Marshmallow validations</em></h3><p>Wait a minute though, I thought Marshmallow also promised safeguards against invalid data before saving it to the database? We saw a bit of that above when we specify our field types and whether or not it’s required, but that’s only a small fraction of what’s available.</p><p>If our Flask backend is also receiving POST requests, we have several options of how we can check that incoming data meets our requirements before taking any further action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/0*d-WpqZtvXplX4ngJ.jpg" /><figcaption><em>3 validation options walk into a club</em></figcaption></figure><p>Marshmallow offers 3 options for us to do so:</p><ul><li><strong>validate</strong>: Use a pre-built validator directly on the field in the schema definition</li><li><strong>validates: </strong>Create a custom function for a specific field in the schema</li><li><strong>validates_schema: </strong>Create a custom function for a specific instance of the schema’s model (the object itself)</li></ul><p>Let’s revisit our Book, Review, and User Schema for an example of each.</p><h4><em>validate</em></h4><p>This option is what you will use most frequently. It covers common use cases like checking length or RegEx matches for strings or range for integers. The full list of choices is available <a href="https://marshmallow.readthedocs.io/en/stable/marshmallow.validate.html">here</a>.</p><pre>from marshmallow import fields, validate<br><br>ACCEPTED_GENRES = [&quot;Poetry&quot;, &quot;Fantasy&quot;, &quot;Historical Fiction&quot;, &quot;Memoir&quot;, <br>                &quot;Literary Fiction&quot;, &quot;Horror&quot;, &quot;Drama&quot;, &quot;Children&#39;s&quot;]<br><br>class BookSchema(ma.SQLAlchemySchema):<br>    # Meta sub-class setup <br><br>    # check the length of the title string<br>    # return the error message if length not met<br>    title = fields.String(validate=validate.Length(min=1, max=150), \<br>                    error=&quot;Title must be less than 150 characters&quot;)<br>    # check that the value for genre appears in the list of accepted genres<br>    genre = fields.String(validate=validate.OneOf(ACCEPTED_GENRES), \<br>                            error=&quot;Genre not valid&quot;)<br>    # check that the integer falls within an accepted range <br>    # (no billion page books!)<br>    page_count = fields.Integer(strict=True, \<br>                    validate=validate.Range(min=1, max=25000), \<br>                    error=&quot;Page count must be between 1 and 25000&quot;)</pre><p>Here we define a rule for our fields in line, e.g. the title must be between 1 and 150 characters, and the genre string must appear in an approved list. Should a validation fail, Marshmallow will return its corresponding error.</p><h4>validates</h4><p>If you want to compare an incoming value for a single field to existing rows in your database, validates can be a good fit.</p><pre>from marshmallow import validates, ValidationError<br><br>class UserSchema(ma.SQLAlchemySchema): <br>    # Meta sub-class setup <br><br>    # add validates decorator and specify the relevant field name<br>    @validates(&quot;username&quot;)<br>    # create an instance method that takes a value for username <br>    def validates_username(self, username):<br>        # check if a user already exists with that username<br>        if User.query.filter(User.username == username).first():<br>                raise ValidationError(&quot;That username is taken&quot;)</pre><p>Here we are checking the &quot;username&quot; field on the User. Our custom function takes in the incoming username and searches the database for a corresponding result. If there’s a user already with that username, Marshmallow will raise an error that it’s taken.</p><h4><em>validates schema</em></h4><p>If the validity of one field depends on another — field A should be greater than field B, or field C should not occur alongside field D — then validates schema is a useful option.</p><p>We can use this to prevent the same user from reviewing the same book twice.</p><pre>from marshmallow import validates_schema, ValidationError<br><br>class ReviewSchema(ma.SQLALchemySchema): <br>  # Meta sub-class setup<br><br>  # any field specifications<br>  # add validates_schema decorator<br>  # no field needed, since it&#39;s looking at the whole object<br>  @validates_schema<br>   def validate_object(self, data, **kwargs):<br>      # check the database to see if there&#39;s already a review<br>      # with the same book and user id <br>      if review := Review.query.filter(Review.book_id == data[&quot;book_id&quot;]) \<br>                          .filter(Review.user_id == data[&quot;user_id&quot;]) \<br>                          .first(): <br>              # raise an error <br>              # that this book has already been reviewed by this user<br>              raise ValidationError(&quot;Book already reviewed&quot;)</pre><p>The book_id and user_id could be valid separately, but if they would occur more than once in the same row, we have Marshmallow raise an error. We check this by querying our review for a row that already has that pairing.</p><h4><em>Test this out!</em></h4><p>You could test these options out directly in the Flask shell with a few key steps.</p><pre><br># instantiate an instance of our book schema class<br># no many=True this time because we are only looking at an individual book<br>book_schema = BookSchema()<br>book_data = { &quot;title&quot;: &quot;The Burning God&quot;, &quot;genre&quot;: &quot;Viral fiction&quot;, &quot;page count&quot;: 656 }<br><br># check the above book_data against our schema<br>book_schema.validate(book_data)<br><br>## Marshmallow returns the following error<br>## {&#39;genre&#39;: [&quot;Must be one of: Poetry, Fantasy, Historical Fiction, \<br>## Memoir, Literary Fiction, Horror, Drama, Children&#39;s.&quot;]}</pre><h3><em>Common errors</em></h3><p>With great flexibility comes great likelihood of errors of your own making. Here’s 3 that may rear their heads and a starting point of where to look.</p><ul><li><strong>ImportError: </strong>This may surface as ImportError: cannot import name &#39;NameOfSchema&#39; from partially initialized module (likely due to circular import) . This can occur if you have mirrored nested fields (e.g. books on reviews and reviews on books) and are importing each schema into each file. You can resolve this by typing one of the schemas as a string, e.g. &quot;ReviewSchema&quot; for the nested reviews field on books, to break the circular import.</li><li><strong>AttributeError: </strong>This may surface as AttributeError: &#39;NameOfSchema&#39; has no attribute &#39;id&#39; Check that you have appropriately defined many=True for any many-to-many or one-to-many relationships and that this schema isn’t trying to interpret many as one .</li><li><strong>ValueError: </strong>This may surface as ValueError: Invalid fields for &#39;NameOfSchema&#39; . Check your nested fields and that you are not trying to serialize a field that’s not exposed on the original schema. For example, if UserSchema wants to display the nested books field with a “description,” but the BookSchema itself does not include a “description” field.</li></ul><h3>Further reading</h3><ul><li><a href="https://marshmallow.readthedocs.io/en/stable/quickstart.html#deserializing-objects-loading">Load</a> (deserialize) &amp; <a href="https://marshmallow.readthedocs.io/en/stable/quickstart.html#serializing-objects-dumping">dump</a> (serialize): Use these Marshmallow methods to convert your data to the appropriate format</li><li><a href="https://flask-marshmallow.readthedocs.io/en/latest/#flask_marshmallow.fields.Hyperlinks">Hyperlinks</a> &amp; <a href="https://en.wikipedia.org/wiki/HATEOAS#:~:text=Hypermedia%20as%20the%20engine%20of,provide%20information%20dynamically%20through%20hypermedia.">HATEOAS</a>: Add Hyperlinks to your schema as shortcuts to subsequent calls for a collection or individual item</li><li><a href="https://marshmallow-sqlalchemy.readthedocs.io/en/latest/api_reference.html#marshmallow_sqlalchemy.SQLAlchemyAutoSchema">Auto-schema</a>: Automatically generate fields for your model’s columns</li></ul><h3>The motherships</h3><ul><li><a href="https://marshmallow.readthedocs.io/en/stable/">Marshmallow</a></li><li><a href="https://flask-marshmallow.readthedocs.io/en/latest/">Flask-Marshmallow</a></li><li><a href="https://marshmallow-sqlalchemy.readthedocs.io/en/latest/index.html">Marshmallow-SQLAlchemy</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a815b2276a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Survival Guide for Flask-SQLAlchemy Queries]]></title>
            <link>https://medium.com/@jesscsommer/survival-guide-for-flask-sqlalchemy-queries-e442bbaf9ad?source=rss-8ca2c24d37b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e442bbaf9ad</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[flask-sqlalchemy]]></category>
            <category><![CDATA[beginner-coding]]></category>
            <dc:creator><![CDATA[Jess Sommerville]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 06:24:14 GMT</pubDate>
            <atom:updated>2023-08-21T00:42:13.057Z</atom:updated>
            <content:encoded><![CDATA[<p>With vanilla SQL, SQLAlchemy, Flask-SQLAlchemy, and many more tools at your disposal, it’s easy to lose track of what syntax you need when and where you need it. Together we’ll look at Flask-SQLAlchemy specifically and how to write queries for a many-to-many relationship. Let’s start by doing a quick inventory of the building blocks available to us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*2UevjiLBk6N_PfuHia0xzA.jpeg" /></figure><h4>What we’re working with</h4><p>These are options for asking a more specific question of your data.</p><ul><li><strong>join( ) : </strong>Connect two tables via a foreign key. For Flask SQL Alchemy, you’ll likely reference the relationship field on your chosen model.</li><li><strong>group_by( ) : </strong>Arrange the data into buckets based on a shared column value. You’ll typically use this with an aggregate function.</li><li><strong>order_by( ) : </strong>Return the data in order of a particular column value. Specify .<strong>desc( ) </strong>for descending order.</li><li><strong>with_entities ( ) : </strong>Return additional information with your query other than what’s provided in the original table.</li><li><strong>filter( ) : </strong>Only return data that matches a condition of your choice.</li></ul><h4>What we get back</h4><p>These are options to select which rows you want back from the database, or what happens if they’re not found.</p><ul><li><strong>first( ) : </strong>Returns the first result that matches the query.</li><li><strong>first_or_404( ) : </strong>Returns a 404 error if there are no results. You won’t have a lot of control over the error itself, but this is handy for when you’re building views for an API.</li><li><strong>all( ) : </strong>Returns every result that matches the query.</li></ul><p>These are some cursory definitions to get us started. For more information, check out the <a href="https://docs.sqlalchemy.org/en/20/">SQLAlchemy</a> and <a href="https://flask-sqlalchemy.palletsprojects.com/en/3.0.x/">Flask-SQLAlchemy</a> docs.</p><h3>Many-to-many tables</h3><p>We’ll walk through some examples using a many-to-many relationship between posts and users. They are connected through post_likes — a user can have liked many posts, and a post can have been liked by many users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*AiCV857tTjEjdW278USvoA.png" /><figcaption>Our example data structure: post_likes connect the post_id and the user who liked it.</figcaption></figure><p>Presume we also have models built in Python for User , Post , and PostLike.</p><h3>Sort posts in descending order</h3><p>To start our Flask SQL alchemy queries, we’ll refer to the name of the model, followed by .query , then any of the options to narrow our search mentioned above.</p><pre>Post.query.order_by(Post.created_at.desc()).all()</pre><p>Here we pass Post.created_at to order_by so that our posts will be returned in order of their created date, which directly corresponds to the created_at column in the posts table and the matching field on the model. Adding .desc() will sort the posts so our most recent is our first result.</p><p>This is a good start for when we are building a GET request and want to get back all of our rows for a particular table. When we have a stronger opinion on how we would like to user our data, we can get more specific.</p><h3>Sort posts in descending order by number of likes</h3><p>If we want to order our posts by number of likes, which we are not storing already in our table, we’ll need to combine a join and a group_by .</p><p>A join with our posts and post_likes tables will bridge the gap so that we can calculate the total number of likes per post.</p><pre>def sort_posts_by_likes():<br>    query = Post.query \<br>    # post_likes is a relationship field on the Post model<br>    # this joins the posts and post_likes tables<br>    .join(Post.post_likes) \<br>    # section the data by common post ids <br>    .group_by(Post.id) \<br>    # count the number of post_likes for that section<br>    # return in descending order by number of likes<br>    .order_by(db.func.count(Post.post_likes).desc()) \<br>    # return information about the post from the table, <br>    # plus the like_count labeled as such<br>    .with_entities(Post.id, Post.content, Post.user_id, \<br>                    db.func.count(Post.post_likes).label(&quot;like_count&quot;)) \<br>    .all()<br>    <br>    # specifies how to format each row returned from our query<br>    posts_by_like = [{<br>        &quot;id&quot;: post.id,<br>        &quot;content&quot;: post.content,<br>        &quot;user_id&quot;: post.user_id,<br>        &quot;like_count&quot;: post.like_count<br>        } for post in query]<br><br>    return posts_by_like<br><br>## example return with the &quot;like_count&quot; additional entity<br>[<br>    {<br>        &quot;content&quot;: &quot;excellent post&quot;,<br>        &quot;id&quot;: 91,<br>        &quot;like_count&quot;: 500,<br>        &quot;user_id&quot;: 2<br>    },<br>    {<br>        &quot;content&quot;: &quot;good post&quot;,<br>        &quot;id&quot;: 8,<br>        &quot;like_count&quot;: 150,<br>        &quot;user_id&quot;: 3<br>    },<br>    {<br>        &quot;content&quot;: &quot;ok post&quot;,<br>        &quot;id&quot;: 37,<br>        &quot;like_count&quot;: 25,<br>        &quot;user_id&quot;: 1<br>    }<br>]</pre><p>Once we join our tables, we can group them in order to perform a calculation on each group. Since we group our posts on their unique id, we can then use db.func.count to tally the total number of posts per group, or per each individual post. We then arrange the posts in descending order by this like count, so the most popular posts are returned first.</p><p>The with_entities() option allows us to list exactly what about each row we would like to return. We can pull directly from columns like we did with id, content , and user_id , but the real utility comes from defining our own “column”. If we specify our db.func.count calculation as another value, we can label it like_count and then use it much more accessibly in other areas of our application.</p><h3>Return users who liked a certain person’s posts</h3><p>Our prior examples have each returned posts, but what if we want to return information about another table? In this example, we’ll look at returning a specific person’s “fan club,” or the usernames for anyone that has liked their posts. We’ll need to join multiple tables in order to accomplish this.</p><pre>def get_likers_for_posts_by(userid):<br>    query = User.query \<br>            # post_likes is a relationship field on the User model<br>            # this joins the users and post_likes tables<br>            .join(User.post_likes) \<br>            # post is a relationship field on the PostLike model<br>            # this joins the post_likes and posts tables<br>            .join(PostLike.post) \<br>            # only include posts written by the relevant user<br>            .filter(Post.user_id == userid) \<br>            .all()<br><br>    # only return the username for each result <br>    # set comprehension in case users have liked multiple posts by this person<br>    unique_users = { user[&quot;username&quot;] for user in users_schema.dump(query) } <br>    <br>    return list(unique_users)<br><br>     ## [ &quot;username1&quot;, &quot;username2&quot;, &quot;username3&quot; ]</pre><p>Since we want to return information about users , we start our query on the User model. We join post_likes and posts so we can get to the column on which we want to filter — user_id , or the author of the post. If that’s the id we received when we invoked, then we return the username for this row in users.</p><p><em>Note: </em>Don’t worry too much about the comprehension for unique users. You’ll need to de-serialize what you retrieve via query but you may do this in a variety of ways. The takeaway is that you can iterate through your results to specify exactly what you get back in the event that you don’t want the typical amount of user information.</p><p>As a reference, this is what the same query would look like in vanilla SQL.</p><pre>SELECT DISTINCT users.username FROM users <br>JOIN post_likes ON users.id = post_likes.user_id <br>JOIN posts ON post_likes.post_id = posts.id <br>GROUP BY posts.id<br>HAVING posts.user_id = ?;</pre><p>I hope this helps to get you started crafting your own queries — see you later for the sequel?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e442bbaf9ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing objects by attribute in Python]]></title>
            <link>https://medium.com/@jesscsommer/comparing-objects-by-attribute-in-python-354d0590f8ea?source=rss-8ca2c24d37b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/354d0590f8ea</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[dunder-method]]></category>
            <category><![CDATA[beginner-coding]]></category>
            <dc:creator><![CDATA[Jess Sommerville]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 00:07:13 GMT</pubDate>
            <atom:updated>2023-06-09T19:01:06.030Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comparing objects by attribute</h3><h4>An intro to enriching your comparisons in Python</h4><p>If you are someone interested in comparing Python objects by attribute, read on; else, exit post. Comparisons (you == the interested party) are crucial to the control flow of many an application.</p><p>We can compare by <strong>value</strong> or by <strong>reference</strong>. Once we know the difference, we can customize what does or does not compare as equal. This is especially handy for complex objects.</p><h3>A tale of two comparisons</h3><p>When we compare by <strong>value</strong>, we’re asking:</p><ul><li>Is the <strong>content </strong>of these two items the same?</li><li>Are the two items <strong>equal?</strong></li></ul><p>When we compare by <strong>reference,</strong> we’re asking:</p><ul><li>Is the <strong>location in memory </strong>for these two items the same?</li><li>Are the two items <strong>identical?</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*aml4L_EtgSemTw3S.jpg" /><figcaption>The forever questions of an object</figcaption></figure><p>That may sound exasperatingly pedantic — let’s take a look at the difference when we compare two lists of integers.</p><h3>== vs is</h3><p>For <a href="https://stackoverflow.com/questions/70347051/comparison-operator-for-value-equality-or-reference-equality">some classes</a>, the == operator that will compare its items by value, whereas is will compare its items by reference.</p><pre>&gt;&gt;&gt; x = [1, 2, 3]<br>&gt;&gt;&gt; y = [1, 2, 3]<br><br>&gt;&gt;&gt; x == y<br># True <br># x and y have the same integers in their list<br><br>&gt;&gt;&gt; x is y <br># False <br># x is remembered separately from y</pre><p>x and y contain the same integers, so they are <strong>equal </strong>when compared by value. They are not <strong>identical</strong><em> </em>until they exist at the same location.</p><pre>&gt;&gt;&gt; x = y <br>&gt;&gt;&gt; x is y<br># True </pre><p>This is all well and good when we are looking at a list of integers, but what about when we are comparing more complex objects?</p><h3>🥁 Introducing rich comparisons</h3><p>The operators &lt;, &lt;=, ==, !=, &gt;, &gt;= each have a corresponding <a href="https://mathspp.com/blog/pydonts/dunder-methods#:~:text=What%20are%20dunder%20methods%3F,__%20or%20__add__%20.">dunder method</a> that you have more control over than you might think. You can create your own version of each method to tell Python how to determine if an object is less than, equal to, greater than another.</p><p>In a recent project with my peers to build a Python and SQLite-driven <a href="https://github.com/jesscsommer/python-word-game">word-guessing game</a>, we did just that. Let’s walk through an example together.</p><h3>What we’re working with</h3><p>Assume we have a Puzzle class with solution and id attributes. We want to compare two Puzzle objects as equal if both of these attributes have the same value.</p><pre>first_puzzle = Puzzle(&quot;wordy&quot;, 1) <br><br>first_puzzle<br># first_puzzle memory location<br># &lt;classes.puzzle.Puzzle object at 0x10099ec40&gt;<br><br>vars(first_puzzle)<br># dictionary for the first_puzzle obj<br># {&#39;_solution&#39;: &#39;wordy&#39;, &#39;id&#39;: 1}<br><br>second_puzzle = Puzzle(&quot;wordy&quot;, 1)<br><br>second_puzzle<br># second_puzzle memory location<br># &lt;classes.puzzle.Puzzle object at 0x10099ecd0&gt;<br><br>vars(second_puzzle)<br># dictionary for the second_puzzle obj<br># {&#39;_solution&#39;: &#39;wordy&#39;, &#39;id&#39;: 1}<br><br><br>first_puzzle == second_puzzle <br># False <br>first_puzzle is second_puzzle<br># False</pre><p>Here we instantiate a Puzzle object with the solution &quot;wordy&quot; and id 1 . If we create another with the same <strong>values, </strong>we will still get a new <strong>reference. </strong>If our game logic at all requires us to compare these two puzzles as equal, it will not work.</p><p>This is where Python’s <strong>rich comparisons</strong> come in. We’ll talk about two of the previously promised dunder methods here: __eq__ and __hash__</p><h3>__eq__</h3><p>Under the hood, when you compare objects using ==, Python calls the __eq__ <a href="https://docs.python.org/3/reference/datamodel.html?highlight=__eq__#object.__eq__">method</a>. By default, Python will leverage is to compare two objects. If we define our own version of the method, however, we can instruct Python to look at particular values or attributes instead.</p><p>Let’s take a look back at how we could do this in our Puzzle class.</p><pre>class Puzzle:<br>    <br>    def __init__(self, solution, id=None):<br>        self.solution = solution<br>        self.id = id <br>    <br>    def __eq__(self, other):<br>        if not isinstance(other, type(self)):<br>            # if the other item of comparison is not also of the Puzzle class<br>            return NotImplemented<br>            # comparison is not supported<br>        return self.solution == other.solution and self.id == other.id<br>        # return True or False based on if self&#39;s attributes match other&#39;s</pre><p>Now when we compare our first_puzzle and second_puzzle , our statement will evaluate to True .</p><pre>first_puzzle == second_puzzle <br># True <br># solution and id attributes are the same<br><br>first_puzzle is second_puzzle<br># False<br># locations in memory are still different </pre><h3>__hash__</h3><p>The one caveat of overriding __eq__ is that now instances of our Puzzle class will not be usable in <a href="https://docs.python.org/3/glossary.html#term-hashable">hashable</a> collections, like sets.</p><p>Sets will make our lives easier should we want to compare two lists of puzzles, so we’ll also define a __hash__ <a href="https://docs.python.org/3/reference/datamodel.html?highlight=__eq__#object.__hash__">method</a> to make this possible.</p><p>This is where we return a value that’s unique and constant through the object’s lifetime. Python recommends creating a tuple with the attributes relevant for the comparison, then returning <a href="https://docs.python.org/3/library/functions.html#hash">its hash value.</a></p><pre>def __hash__(self):<br>        return hash((self.solution, self.id))</pre><h3>Why is this useful?</h3><p>If you are mapping your Python classes to a database, you may instantiate objects from many methods — one that gets all rows, finds a row by id, etc. If two objects with the exact same attributes from the exact same row in your database don’t compare as equal, you’re trapped when it’s time to add new features.</p><p>In our word-guessing game, we may want to start by showing the player a list of their unplayed puzzles to choose from. Now that we have set up our __eq__ and __hash__ methods, we can do this in a few lines of code.</p><p>If we have a list for all_puzzles and your_puzzles , we can convert them to sets to quickly find the <a href="https://www.geeksforgeeks.org/python-set-difference/">difference</a> between two sets of puzzles.</p><pre>all_puzzles<br># dictionaires for each puzzle: <br># {&#39;_solution&#39;: &#39;wordy&#39;, &#39;id&#39;: 1}<br># {&#39;_solution&#39;: &#39;snake&#39;, &#39;id&#39;: 2 }<br><br>your_puzzles<br># dictionaries for your played puzzles:<br># {&#39;_solution&#39;: &#39;wordy&#39;, &#39;id&#39;: 1}<br><br><br>unplayed_puzzles = list(set(all_puzzles) - set(your_puzzles))<br># dictionaires for each unplayed puzzle: <br># {&#39;_solution&#39;: &#39;snake&#39;, &#39;id&#39;: 2 }</pre><p>Our player’s only unplayed puzzle is “snake” so that’s all we find in unplayed_puzzles .</p><p>If we had not added our __eq__ and __hash__ methods, unplayed_puzzles would always equal all_puzzles . There would never be any overlap with objects at the same memory location, so there would be nothing to subtract to create that difference. Now we are free to compare our objects in the way that we would expect.</p><p>Given how comparison can power so many conditions, and conditions can power so much of our applications, you can imagine the increased control this provides as you work with more complex data. For more nuts and bolts of how these methods work, check out the resources below.</p><h3><strong><em>References</em></strong></h3><p><a href="https://www.blog.pythonlibrary.org/2017/02/28/python-101-equality-vs-identity/">Python equality vs. identity</a></p><p><a href="https://docs.python.org/3/reference/datamodel.html?highlight=__eq__#object.__eq__">object.__eq__</a>(self)</p><p><a href="https://docs.python.org/3/reference/datamodel.html?highlight=__eq__#object.__hash__">object.__hash__</a>(self)</p><p><a href="https://stackoverflow.com/questions/1227121/compare-object-instances-for-equality-by-their-attributes">Compare object instances by attributes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=354d0590f8ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[But it works! How and when to refactor your code]]></title>
            <link>https://medium.com/@jesscsommer/but-it-works-how-and-when-to-refactor-your-code-2b98ae26c98f?source=rss-8ca2c24d37b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b98ae26c98f</guid>
            <category><![CDATA[beginner-coding]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Jess Sommerville]]></dc:creator>
            <pubDate>Fri, 19 May 2023 02:57:52 GMT</pubDate>
            <atom:updated>2023-05-19T03:42:10.970Z</atom:updated>
            <content:encoded><![CDATA[<h4>An introductory look at refactoring in a React app</h4><p>When you finally get a feature to work, it feels like time to raise your fists into the air then pour a celebratory cup of coffee. Once you or your peers start to build on top of the feature, however, that coffee has long grown cold and explaining your code can take a sour turn.</p><p>Maybe your code works, but is it legible to your team? Is it reusable? Is it now making your life harder? Getting the “ick” when reviewing your codebase is common enough that it’s had a nickname since the ‘90s — <strong>code smells</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*twk8vPU039kxZWWTKA1lKA.jpeg" /><figcaption>Good code doesn’t require an art history paper</figcaption></figure><h3>Code smells</h3><blockquote><strong>Code smells </strong>are any characteristics of your code that “stink” of a larger problem.</blockquote><p>Think of confusing naming conventions, exceedingly long lines of code, copied and pasted logic, passing or returning unused data. Check out more smells by application, class, or method-level <a href="https://en.wikipedia.org/wiki/Code_smell">here</a>.</p><p>As a new programmer, it may be tempting to ignore that intuition so that you can focus on the next set of features. And yet this is the time to <strong>refactor.</strong></p><blockquote>Refactoring is when you rewrite your code in a way that improves its logic without changing its functionality.</blockquote><p>Any writer will tell you that the only writing is rewriting (thanks, <a href="https://www.goodreads.com/quotes/1025221-the-only-kind-of-writing-is-rewriting">Hemingway</a>), and it’s no different when writing lines of code. Taking the opportunity to ask yourself how <em>should</em> this work, not just how <em>can</em> it work, can lead to the stickiest learnings early in your programming journey.</p><p>Not to mention this can help minimize <a href="https://enterprisersproject.com/article/2020/6/technical-debt-explained-plain-english"><strong>technical debt</strong></a>, or code that works now but that we’ll need to fix later when it’s more difficult to do so.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FaDlSQv0oGtavjwM6s3%2Fvideo&amp;display_name=GIPHY&amp;url=https%3A%2F%2Fgiphy.com%2Fclips%2Fart-loop-3d-aDlSQv0oGtavjwM6s3&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2FaDlSQv0oGtavjwM6s3%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="480" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/69d7776da068705ce736c71a54fd9c98/href">https://medium.com/media/69d7776da068705ce736c71a54fd9c98/href</a></iframe><h3>What to refactor</h3><p>When you’re ready to refactor, look for opportunities to:</p><ul><li>Remove duplicate code</li><li>Move functionality to the most appropriate place</li><li>Re-organize your data structure and modifications</li><li>Abstract your overarching logic and delegate further responsibilities</li><li>Simplify your conditional expressions</li></ul><p>These are high-level categories for when you’re just getting started learning how to refactor; they are far from exhaustive. For a deeper dive, and for potential optimizations for each of these scenarios, check out the resources linked at the bottom of this article.</p><h3>React app example</h3><p>When you learn a new language or library, you might still think in an old one when writing your code. Remember to sanity-check if you are working with or against the benefits of your new library.</p><p>That was just the case when building <a href="https://github.com/nolannash/group-5-phase2-west-041023">a React app</a> with my peers this week (funnily enough, about sharing recipes … talk about smells 😉). We set up our <a href="https://www.npmjs.com/package/json-server">own JSON-server</a> to PATCH and POST recipes via <a href="https://medium.com/byte-sized-react/controlled-forms-in-react-68e59362a119">a controlled form</a>.</p><p>In our initial builds, each of these requests required a separate form — one to edit and one to add. The returns were nearly identical in terms of their inputs. The main differentiators were:</p><ul><li>How you got to the form and where you ended up (/cookbook/:id/edit vs /recipes/new )</li><li>What you saw on the form (preloaded data for that cookbook recipe vs. empty fields to create a new one)</li><li>What happened on submit (PATCH vs. POST)</li></ul><p>While we need to account for those differences, one of the main benefits of React is component reusability. If you give each component a narrowly scoped responsibility, then you can render it wherever that functionality is needed.</p><p>Let’s take a look at how that can work inside of a singular Form component. We’ll assume that we are using <a href="https://reactrouter.com/en/main/start/overview">React Router</a> for this example.</p><pre>// inside our Form component <br><br>// call the useParams() hook from React Router<br>// destructure the response to save the id to a variable<br>const { id } = useParams()<br><br>// set a state to keep track of our form data and control its input values<br>const [formData, setFormData] = useState(initialState)<br><br>// destructuring of our state for later use<br>const { recipeName } = formData <br><br>useEffect(() =&gt; {<br><br>// check if we have an id from the url,<br>// the data for which we should display as our initial form values<br><br>    if (id) {<br>        fetch(`endpoint/${id}`)<br>        .then(res =&gt; res.json())<br>        .then(setFormData)<br>  }, [id])</pre><p>We know that the user will land on this form at either /cookbook/:id/edit or /recipes/new . If we have an id parameter, we know we have something to edit. /cookbook/1/edit would suggest we should be editing the object with an id of 1, and const { id } = useParams() would have id equal to 1. If we do not have any id, we know we are looking to create something entirely new.</p><p>That can inform our logic for what we display in the form’s inputs. By default, we’ll set our formData state to an initialState , an assumed object with keys matching our database structure and empty values.</p><p>If we do have an id to look for, however, we’ll go fetch that object’s data from an interpolated url and setFormData equal to the return. Once that state is reset, the form input values will update accordingly. We’ll refetch whenever the id changes.</p><p>We still want two different actions on submit. Let’s create a simple ternary expression to account for each scenario.</p><pre>const handleSubmit = (e) =&gt; {<br>  e.preventDefault()<br><br>  // if we have an id, modify with a PATCH request in our helper function<br>  // if not, create a new data entry<br><br>  id ? patchData() : postData()<br><br>  // reset the form values <br>  setFormData(initialState)<br>}</pre><p>If we have an id , if we are editing, invoke our helper function with our PATCH request logic ready to go. If not, POST a new recipe instead. This keeps our submit function lightweight even though it’s accounting for “two” forms — it prevents the page from refreshing, invokes a function to process the new user inputs, then clears the form.</p><pre>// our JSX return in our Form component<br><br>return (<br>  // trigger one submit event regardless if we are editing or adding <br>  &lt;form onSubmit={handleSubmit}&gt;<br><br>      // control our input values with our formData state<br>      // which is either the initial empty value or what we fetched for this id<br><br>      // assume a handleChange function exists to update state as user types<br><br>      &lt;input name=&#39;recipeName&#39; onChange={handleChange} value={recipeName} /&gt; <br>      &lt;input type=&#39;submit&#39; /&gt; <br>  &lt;/form&gt;<br>)</pre><p>We’ll keep it simple here with one input for the recipeName that we destructured above. We could have as many as we have keys on our recipe object and in our formData state. Now that we are working with React instead of against it, we can more easily adapt as our data or UI changes.</p><p>Some other reasons to refactor in your React app may include:</p><ul><li>Sending eerily similar data to different components (Are you sure you can’t render the same component with different props, even if the data is from different sources?)</li><li><a href="https://blog.logrocket.com/solving-prop-drilling-react-apps/">Prop drilling</a>, or passing props to components for the sole purpose of getting them further down the prop chain</li><li>Setting states for information you have access to elsewhere</li></ul><h3>Additional resources</h3><ul><li><a href="https://refactoring.guru/refactoring">Refactoring Guru</a>: Your one-stop shop for dirty vs. clean code, how to tell the difference, and what to do about it</li><li><a href="https://martinfowler.com/books/refactoring.html">Refactoring</a>: This is The Book™️</li></ul><p>I hope this introduction helps to make refactoring a little less intimidating. Now get cookin’!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b98ae26c98f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How do I tell if an array contains any element from another?]]></title>
            <link>https://medium.com/@jesscsommer/how-do-i-tell-if-an-array-contains-any-element-from-another-ade45e6d2ca0?source=rss-8ca2c24d37b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ade45e6d2ca0</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[beginner-javascript]]></category>
            <category><![CDATA[array-methods]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jess Sommerville]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 05:58:33 GMT</pubDate>
            <atom:updated>2023-04-28T05:58:33.261Z</atom:updated>
            <content:encoded><![CDATA[<p>A common user experience is to filter results to your heart’s content — just think about the last time you got hungry and searched for restaurants with an average rating &gt; 4 stars within a couple-mile radius.</p><p>When working on our first project for Flatiron School, my team wanted to offer our users the same freedom. We pulled in data from the<a href="https://www.nps.gov/subjects/developer/api-documentation.htm#/"> National Parks Service API</a>, thinking it would be great to build a single-page application where you can filter parks by activity or state.</p><p>As a new programmer, however, it can be tricky to take external data and manipulate it the way you need. Much more difficult than convincing yourself that yes, you really must plan a trip to Acadia National Park.</p><p>Here are a few approaches to filter arrays in JavaScript that can help in a similar situation, specifically by finding the <strong>intersection</strong> of two arrays. You can think about an intersection<strong> </strong>as<strong> </strong>the collection of elements that are present in both arrays.</p><h3>Array methods</h3><p>Let’s start by reviewing a couple helpful methods at our disposal. We will use these in our examples below.</p><h4>includes( )</h4><ul><li>Takes one parameter, our “search term”</li><li>Returns true or false based on whether or not the parameter exists in the array</li></ul><h4>filter( )</h4><ul><li>Takes one parameter, a callback function. We can create any function here that evaluates to true for the elements we want to keep in the results, and false otherwise. includes() above matches that criteria — this will come in handy later.</li><li>Returns a copy of the array with the results</li></ul><p>These are quick definitions. You can find a full reference for each method in the MDN <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes">here</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">here</a>.</p><h3>Comparing flat arrays</h3><p>If our arrays do not have any nested elements, filter() and includes() can help us return common elements with just a few lines of code.</p><p>To keep with our parks theme, let’s say we have two arrays — one for available summer activities, and one for winter.</p><pre>const summer = [&#39;hiking&#39;, &#39;swimming&#39;, &#39;guided tours&#39;, &#39;museum exhibits&#39;]<br><br>const winter = [&#39;skiing&#39;, &#39;snowboarding&#39;, &#39;guided tours&#39;, &#39;museum exhibits&#39;]</pre><p>If we’re interested only in year-round activities, we want an array with only the strings from winter and summer. We can use filter() on our summer array, then create callback function that takes one activity at a time and checks for its presence in our winter array.</p><pre>const yearRound = summer.filter(activity =&gt; winter.includes(activity))<br><br>// =&gt; [ &#39;guided tours&#39;, &#39;museum exhibits&#39; ]</pre><p>You might think about the approach here as:</p><ul><li>summer.filter Start with the summer array</li><li>activity =&gt; Look at each activity (string)</li><li>winter.includes(activity) Determine if the winter array has a matching activity (string). If yes, return in the resulting copy of the summer array.</li></ul><h3>Comparing nested arrays</h3><p>Chances are that the arrays we’d like to compare will not be simple strings, especially if working with an external API. In this example, we’ll look at how we could check if a nested array contains any elements of another.</p><p>Let’s say we now have an array of objects to represent our parks. Each park has a name, state, and available activities. The latter has its own array as its value.</p><p>Separately, we have an array we’ll call userInput — whatever activities our users have selected as interesting to them and want to interact with in our app.</p><pre>const parks = [ <br>  {<br>    name: &#39;Acadia National Park&#39;, <br>    state: &#39;Maine&#39;,<br>    activities: [&#39;boating&#39;, &#39;camping&#39;, &#39;fishing&#39;, &#39;skiing&#39;]<br>  }, <br>  {<br>    name: &#39;Olympic National Park&#39;, <br>    state: &#39;Washington&#39;,<br>    activities: [&#39;hiking&#39;, &#39;snowshoeing&#39;, &#39;tubing&#39;, &#39;kayaking&#39;]<br>  }, <br>  {<br>    name: &#39;Arches National Park&#39;, <br>    state: &#39;Utah&#39;,<br>    activities: [&#39;canyoneering&#39;, &#39;climbing&#39;, &#39;stargazing&#39;, &#39;horse trekking&#39;]<br>  }<br>] <br><br>const userInputs = [&#39;hiking&#39;, &#39;stargazing&#39;]</pre><p>Remember includes() takes a single search element. If we try to match our exact solution above, with something like parks.filter(park =&gt; userInputs.includes(park.activities)), we are not going to get any results.</p><p>So how do we access that nested array? We’ll need to expand on our callback function to move from the parks object down to parks.activities</p><pre>const filteredParks = parks.filter(park =&gt; {<br> *// add filter to the parks array and pass each park to the callback function<br><br>  for (const activity of park.activities) {<br>*// go through each activity for this park <br><br>    if (userInputs.includes(activity)){<br>*// if our user inputs array also has the same activity string<br><br>      return true <br>*// this park meets our condition<br>*// include the park in the array copy returned by .filter()<br><br>    } <br>  }<br>})<br><br>/* =&gt; [<br>  {<br>    name: &#39;Olympic National Park&#39;,<br>    state: &#39;Washington&#39;,<br>    activities: [ &#39;hiking&#39;, &#39;snowshoeing&#39;, &#39;tubing&#39;, &#39;kayaking&#39; ]<br>  },<br>  {<br>    name: &#39;Arches National Park&#39;,<br>    state: &#39;Utah&#39;,<br>    activities: [ &#39;canyoneering&#39;, &#39;climbing&#39;, &#39;stargazing&#39;, &#39;horse trekking&#39; ]<br>  }<br>]<br>*/</pre><p>Here our for loop gets us closer to the information we actually care about, the activities, until we can check if the user’s interest includes an activities associated with a particular park.</p><p>Since the callback function for filter() should return a truthy or falsey value, we manually return true if our user’s interests include our activity string. In our results, we end up with an Olympic National Park match on &#39;hiking&#39; and an Arches National Park match on &#39;stargazing&#39; .</p><p>If you’re not working with much data, this can do the job. It’s important to note, however, that currently we are going through <em>every </em>user-selected activity for <em>every </em>element of <em>every </em>activities array on our parks. This will become more inefficient should the length of our arrays increase.</p><p>One way to mitigate this is to utilize a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set">set</a>. At their simplest level, sets are a collection of values. They have some important distinctions from arrays, and for a more thorough introduction, I’d recommend this video on the <a href="https://www.youtube.com/watch?v=4pRkrVwpLQo">Complete Guide to JS Sets</a>.</p><p>What we need to know today is that we can check whether an element exists in a set more quickly than in an array. No matter how long our array for park.activities becomes, if we create a set from the values, we can locate our activity of interest in the same amount of time.</p><pre>const filterParks = parks.filter(park =&gt; {<br>*// add filter to the parks array and pass each park to the callback function<br><br>  const parkActivities = new Set(park.activities)<br>*// create a set with all the activities for this specific park <br><br>  for (const activity of userInputs) {<br>*// for each activity the user selected <br><br>      if (parkActivities.has(activity)) {<br>*// if the set has that same activity string<br><br>        return true<br>*// this park meets our condition<br>*// include the park in the array copy returned by .filter()<br>      }<br>  }<br>})<br><br>/* =&gt; [<br>  {<br>    name: &#39;Olympic National Park&#39;,<br>    state: &#39;Washington&#39;,<br>    activities: [ &#39;hiking&#39;, &#39;snowshoeing&#39;, &#39;tubing&#39;, &#39;kayaking&#39; ]<br>  },<br>  {<br>    name: &#39;Arches National Park&#39;,<br>    state: &#39;Utah&#39;,<br>    activities: [ &#39;canyoneering&#39;, &#39;climbing&#39;, &#39;stargazing&#39;, &#39;horse trekking&#39; ]<br>  }<br>]<br>*/</pre><p>Here we use the has() method for our set rather than the includes() on our array. The method also takes a search element parameter to look for in the set.</p><p>In this updated approach, we still need to iterate through each park, but not each nested activities array. For more on intersections and sets, check out <a href="https://www.geeksforgeeks.org/how-to-perform-intersection-of-two-sets-in-javascript/">this example</a> from Geeks for Geeks.</p><p>And there you have it, we’ve filtered our array based on the contents of another. I hope this helps you to get started working with filters in your own applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ade45e6d2ca0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>