Completing 4 JavaScript .filter() Method Challenges
Tags: javascript, algorithms
Published: 2021-06-07 05:02:45

As a personal challenge to learn and grow my JavaScript skills, I will be digging into some of the most popular methods and properties the language has to offer. Over the next several weeks, I will be completing a series of algorithm challenges that require the use of specific methods/properties.

The first method in my challenge is `filter()`.

According to the [Mozilla documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter):
> The Javascript array filter() creates a new array of elements from an existing array that meets a specified condition.

**Time Complexity:** O(n)

I decided to challenge myself with the `.filter()` method first because it's super useful when it comes to dealing with data. Pretty much every website with a catalogue of data (products, articles, users, etc.) needs a way to filter and return only the data necessary to perform an action. I know I have done many web searches and used the handy filtering options to narrow down the results to find exactly what I want.

_If you've never used the `filter()` method, check out this awesome [documentation from GeeksforGeeks](https://www.geeksforgeeks.org/javascript-array-filter-method/) for more information._

## Challenge: Filter An Array of Objects
```javascript
// create a function that filters an array of objects to find hotels rated at least N stars or higher

const data = [
    {
        name: 'Hilton',
        rating: 4.7
    },
    {
        name: 'Best Western',
        rating: 3.8
    },
    {
        name: 'Bob\'s Hotel',
        rating: 2.5
    },
    {
        name: 'Marriot',
        rating: 4.2
    }
];

function filterByRating(data, ratingMinimum, ratingMaximum) {
    data = data.filter(data => data.rating >= (ratingMinimum ?? 0));
    data = data.filter(data => data.rating <= (ratingMaximum ?? 5));
    return data;
}

const hotelsWithAtLeast4Stars = filterByRating(data, 4);
console.log(hotelsWithAtLeast4Stars);
// OUTPUT
// [{ name: 'Hilton', rating: 4.7 }, { name: 'Marriot', rating: 4.2 } ]

const hotelsWithAtLeast3Stars = filterByRating(data, 3);
console.log(hotelsWithAtLeast3Stars);
// OUTPUT
// [
//     { name: 'Hilton', rating: 4.7 },
//     { name: 'Best Western', rating: 3.8 },
//     { name: 'Marriot', rating: 4.2 }
//   ]

const hotelsBetween3and4Stars = filterByRating(data, 3, 4);
console.log(hotelsBetween3and4Stars);
// OUTPUT
// [ { name: 'Best Western', rating: 3.8 } ]

const hotelsWith3orLessStars = filterByRating(data, null, 3);
console.log(hotelsWith3orLessStars);
// OUTPUT
// [ { name: "Bob's Hotel", rating: 2.5 } ]
```

## Challenge: Filter An Array of Numbers/Strings
```javascript
// Challenge #1
// Create a function that filters strings by length given two arguments: minimum length, maximum length
// Either argument may be missing. if both are missing, return the original array

function filterStringsByLength(arrayOfStrings, minLength, maxLength) {
  arrayOfStrings = arrayOfStrings.filter(string => string.length >= (minLength ?? 0));
  arrayOfStrings = arrayOfStrings.filter(string => string.length <= (maxLength ?? string.length));
  return arrayOfStrings;
}

const arrayOfStrings = ['', 'a', 'bc', 'def', 'ghij', 'klmno', 'pqrstu', 'vwxyz12'];
const nums = [1,2,3,4,5]

const wordsAtLeast3Characters = filterStringsByLength(arrayOfStrings, 3);
console.log(wordsAtLeast3Characters);
// OUTPUT
// [ 'def', 'ghij', 'klmno', 'pqrstu', 'vwxyz12' ]

const wordsNoLongerThan5Characters = filterStringsByLength(arrayOfStrings, null, 5);
console.log(wordsNoLongerThan5Characters);
// OUTPUT
// [ '', 'a', 'bc', 'def', 'ghij', 'klmno' ]

const wordsAtLeast3CharactersAndNoLongerThan5Characters = filterStringsByLength(arrayOfStrings, 3, 5);
console.log(wordsAtLeast3CharactersAndNoLongerThan5Characters);
// OUTPUT
// [ 'def', 'ghij', 'klmno' ]

let minAndMaxNotProvided = filterStringsByLength(arrayOfStrings);
console.log(minAndMaxNotProvided);
// OUTPUT
// ['', 'a', 'bc', 'def', 'ghij', 'klmno', 'pqrstu', 'vwxyz12']


// Challenge #2
// Create a function that filters an array of numbers, given two arguments: minimum and maximum.
// Either argument may be missing. if both are missing, return the original array

function filterNumbersBySize(arrayOfNumbers, minSize, maxSize) {
  arrayOfNumbers = arrayOfNumbers.filter(number => number >= (minSize ?? number));
  arrayOfNumbers = arrayOfNumbers.filter(number => number <= (maxSize ?? number));
  return arrayOfNumbers;
}

const arrayOfNumbers = [-12, -4, 0, 2, 11, 63, 1001];

const numbersMinus5AndUp = filterNumbersBySize(arrayOfNumbers, -5);
console.log(numbersMinus5AndUp);
// OUTPUT
// [ -4, 0, 2, 11, 63, 1001 ]

const numbersNoGreaterThan10 = filterNumbersBySize(arrayOfNumbers, null, 10);
console.log(numbersNoGreaterThan10);
// OUTPUT
// [ -12, -4, 0, 2 ]

const numbersBetweenMinus4And11 = filterNumbersBySize(arrayOfNumbers, -4, 11);
console.log(numbersBetweenMinus4And11);
// OUTPUT
// [ -4, 0, 2, 11 ]

minAndMaxNotProvided = filterNumbersBySize(arrayOfNumbers);
console.log(minAndMaxNotProvided);
// OUTPUT
// [-12, -4, 0, 2, 11, 63, 1001]
```

## Challenge: Filter Out Repeated Values
```javascript
// Write a function to filter out any duplicates in an array
// Input type is an array of strings and/or numbers

function removeDuplicates(array) {
  return array.filter((item, index) => index === array.indexOf(item));
}

const arrayOfStrings = ['aa', 'bb', 'cc', 'dd', 'ee', 'aa', 'bb', 'cc'];

const arrayOfStringsWithoutDupes = removeDuplicates(arrayOfStrings);
console.log(arrayOfStringsWithoutDupes);
// OUTPUT
// [ 'aa', 'bb', 'cc', 'dd', 'ee' ]

const arrayOfNumbers = [0, 1, 1, 2, 3, 3, 3, 4, 5];

const arrayOfNumbersWithoutDupes = removeDuplicates(arrayOfNumbers);
console.log(arrayOfNumbersWithoutDupes);
// OUTPUT
// [ 0, 1, 2, 3, 4, 5 ]

const arrayOfNumbersAndStrings = arrayOfStrings.concat(arrayOfNumbers);

const arrayOfNumbersAndStringsWithoutDupes = removeDuplicates(arrayOfNumbersAndStrings);
console.log(arrayOfNumbersAndStringsWithoutDupes);
// OUTPUT
// [ 'aa', 'bb', 'cc', 'dd', 'ee', 0, 1, 2, 3, 4, 5 ]
```

[View the code on my Github.](https://github.com/twinfred/JavaScript_Methods_And_Properties/tree/main/filter())