DEV Community

Manav Misra
Manav Misra

Posted on

Filtering An Array

This post assumes prior knowledge of:

  1. Array Iterations
  2. Callback Functions


const catalog = [
  { name: 'Hammer', desc: 'A πŸ”¨', price: 1.5, id: 1 },
  { name: 'Chainsaw', desc: 'Cut up πŸ§Ÿβ€β™‚οΈs.', price: 11.5, id: 2 },
  {
    name: 'Frying Pan',
    desc: 'For πŸ‘¨πŸ½β€πŸ³ing πŸ₯˜.',
    price: 10.5,
    id: 3
   },
   { name: 'Spatula', desc: 'Use it for grilling.', price: 7.5, id: 4 },
   {
     name: 'Airplane',
     desc: 'For flying around!',
     price: 100000000.5,
     id: 5
    },
    { name: 'Car', desc: 'For driving.', price: 10000.5, id: 6 }
]

// TODO: Create a new Array that contains all of the items with a 'price' less than $100.

Enter fullscreen mode Exit fullscreen mode

const under100 = catalog.fiter(function(item) {
        return item.price <= 100;
})
Enter fullscreen mode Exit fullscreen mode

The filter method is part of Array.prototype. This means that we can call on it on anything that is a bona fide Array ( catalog πŸ‘†πŸ½). It takes in a callback function and returns a new Array (under100 πŸ‘†πŸ½). filter filters an Array by iterating over each element and passing it into its callback function. If the callback function returns true, then that element is 'added' to the returned Array.

In our example above, item represents one of the Objects in the Array catalog. If item's price references a value less than or equal to 100, item is included in under100. As you can see, this is why our callback function must return either true or false - this is how we are able to perform 'filtering.'

When filtering, the original Array (catalog) is not mutated (changed) in any way. Instead a separate, new Array is created. Avoiding mutations is usually desirable and is a fundamental of the functional programming paradigm.

♻️ Refactoring Our Code Using ES6 Arrow Syntax ➑️

const under100 = catalog.fiter(item => item.price <= 100)

Top comments (0)