DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,911 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Brian Barbour
Brian Barbour

Posted on

Array.filter() Is Awesome

This weekend I was working on my React project and in one of my components I needed to delete from a list. The data from the list was stored in state with an array.

I learned multiple ways to manipulate arrays in my studies. You have .pop(), .unshift(), .slice(), .splice() and... .filter(). My first decision when picking the best method was to think about React. State is immutable. That meant that I couldn't effect it directly. Fine, no problem--that meant I could discard a few of these options.

It left me with .slice() and .filter().

My instinct was to reach for .slice(). But, I decided to really look at .filter() as I had seen other people use it in React in examples.

After pouring over the documentation on MDN, it clicked to me why it's such a nice method for something like deleting from an array.

I'm already using .map() to iterate over the array to render the list. That gives me the index as one of the arguments. I figured I could then pass that as a prop alongside the state to my component. Inside the component I need only create a handleDelete function that triggers onClick.

Inside the deleteItem the .filter() takes a callback function that returns a boolean based on a condition. Once the entire array has been evaluated, it spits out a new array with of those indexes that were determined as true.

To veteran javascript devs this is probably a no brainer, but I'm glad I realized how useful .filter() can be.

Here's an example of my component:

const ItemList = ({ inventory }) => {
  const [list, setList] = inventory;
  const deleteItem = index => {
    const newInventory = list.filter(
      (item, itemIndex) => index !== itemIndex
    );
    return setList([...newInventory]);
  };
  return (
    <tbody>
      {list.length > 0 ? (
        list.map((item, index) => {
          return (
            <tr key={index}>
              <td>
                {item}{" "}
                <div className="is-pulled-right">
                  <button
                    className="delete is-small"
                    onClick={e => deleteItem(index)}
                  />
                </div>
              </td>
            </tr>
          );
        })
      ) : (
        <tr>
          <td>
            <em>Empty.</em>
          </td>
        </tr>
      )}
    </tbody>
  );
};

export default ItemList;
Enter fullscreen mode Exit fullscreen mode

Top comments (9)

Collapse
 
karandikarmihir profile image
Mihir Karandikar

I almost forgot! Nice article. It wasn't new to me, but will certainly help newcomers :D

Collapse
 
bbarbour profile image
Brian Barbour Author

Thanks! It's always nice to learn a method, but it's best when it finally clicks and you find a great way to use it.

Collapse
 
karandikarmihir profile image
Mihir Karandikar

True that!

Collapse
 
karandikarmihir profile image
Mihir Karandikar

Another way is to normalize the array into an object and directly deleting the desired object. Check out "normalizr" library when you have free time.

Collapse
 
dance2die profile image
Sung M. Kim

Is this the library you are referring to?

paularmstrong / normalizr

Normalizes nested JSON according to a schema

normalizr build status Coverage Status npm version npm downloads

Install

Install from the NPM repository using yarn or npm:

yarn add normalizr
npm install normalizr

Motivation

Many APIs, public or not, return JSON data that has deeply nested objects. Using data in this kind of structure is often very difficult for JavaScript applications, especially those using Flux or Redux.

Solution

Normalizr is a small, but powerful utility for taking JSON with a schema definition and returning nested entities with their IDs, gathered in dictionaries.

Documentation

Examples

Quick Start

Consider a typical blog post. The API response for a single post might look something like this:

{
  "id": "123"
  "author": {
    "id": "1"
    "name": "Paul"
  }
  "title"
…
Collapse
 
karandikarmihir profile image
Mihir Karandikar

That's right.

Collapse
 
falco467 profile image
falco467

Why are you calling setList like that? The array is new and not used anywhere else, no need to copy it again!?

Collapse
 
bbarbour profile image
Brian Barbour Author

setList is the useState hook. That's why.

Collapse
 
vadimsolovei profile image
Vadim Solovei

Sorry, but can you explain in more detail?

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!