Fiction Filter explainer

Aim of the puzzle: Use the .filter() array method to create a new array containing only certain elements from another array.
Walk through of solution: The .filter() array method is used to iterate through an array of elements and apply a test to each one. If the element passes the test, then that element is copied into a new array. The original array is not modified.

The first line of code in this puzzle imports the bookShelf array from additional code. This array contains objects that have the property genre set to either 'science fiction' or 'fantasy'.

The function getSciFi() contains the test that we will use in the .filter() array method. This function will check if the genre property is 'science fiction', and return either true or false.

The sciFi variable will use this function as the test for .filter() to iterate through the bookShelf array and copy only the elements that pass the test. The for…of loop will then print these books to the console.

To complete the puzzle, add .filter(getSciFi) to the end of let sciFi = bookShelf.

Sample code solution:

import { bookShelf } from 'grasshopper.books';

function getSciFi(book) {
    return book.genre === 'science fiction';
}

let sciFi = bookShelf.filter(getSciFi);

for (let book of sciFi) {
    console.log(book.title + ' by ' + book.author);
}

Javascript Concepts: Array Methods, .filter(), Variable Declarations with Let, For…of Loops, Function Declarations, Imports
Additional Code (hidden code that runs before the puzzle’s code):

const bookShelf = [
  {
    title: 'The Chamber of Secrets',
    author: 'JK Rowling',
    genre: 'fantasy'
  },
  {  
    title: 'Discworld',
    author: 'Terry Pratchett',
    genre: 'fantasy'
  },
  {
    title: 'Jonathan Strange & Mr Norrell',
    author: 'Susanna Clarke',
    genre: 'fantasy'
  },
  {
    title: 'The Hitchhiker\'s Guide to the Galaxy',
    author: 'Douglas Adams',
    genre: 'science fiction'
  },
  {
    title: 'Dune',
    author: 'Frank Herbert',
    genre: 'science fiction'
  }
];


2 Likes