Osi
Osi

Reputation: 1

Using filter() on a mapped array of objects but with omitting the data used for filtering

I have the following mapped array of objects on which I'm Using filter(). It is a list of TO DO tasks, from which I want to filter out only tasks that haven't been done yet, but without the false value indicating they haven't been done yet). In other words, I just want to display the tasks themselves, if indeed, they weren't done yet.

The purpose of the code is learning on a good way to omit that data (false) declaration from the filtered content.

let todos = [
    {
        todo: 'Buy apples',
        done: false
    },
    {
        todo: 'Wash car',
        done: true
    },
    {
        todo: 'Write web app',
        done: false
    },
    {
        todo: 'Read MDN page on JavaScript arrays',
        done: true
    },
    {
        todo: 'Call mom',
        done: false
    }
];

I tried:

unfinishedTasks = todos.map( (e)=> e).filter( (e)=> e.done == false);

as well as:

unfinishedTasks = todos.filter( (e)=> e).map( (e)=> if ( e.done == false ) {e.todo} );

The first outputs basically correct - the false todo's are there, but with the false keyword near them - the keyword I'd like to omit, of course:

[{"todo":"Buy apples","done":false},{"todo":"Write web app","done":false},{"todo":"Call mom","done":false}]

The second outputs:

Unexpected token "if".

What I desire (ommiting the false keyword from the output):

["Buy apples", "Write web app", "Call mom"]

I run the code in teamtreehouse.com execution snippet. To test it there, one must be a registered Treehouse student.

I might need to use another filter() on the filtered content, or using some if-than statement? I don't have a clue.

Upvotes: 0

Views: 18

Answers (1)

TimoStaudinger
TimoStaudinger

Reputation: 42460

First filter by item.done, then map to item.todo:

const todos = [{ todo: 'Buy apples', done: false }, { todo: 'Wash car', done: true }, { todo: 'Write web app', done: false }, { todo: 'Read MDN page on JavaScript arrays', done: true }, { todo: 'Call mom', done: false } ];

const out = todos
  .filter(item => !item.done)
  .map(item => item.todo);

console.log(out); // ["Buy apples", "Write web app", "Call mom"]

Upvotes: 1

Related Questions