Filtering through an object and returning items through a filter

Hi Everyone

I am trying to write a function, when given a list of objects, returns the list of all active items. My array of objects would like like this

const list = [
                 { id: 1, active: true },
                 { id: 2, active: false },
                 { id: 3, active: true  },
                 { id: 4, active: false }
               ];

I would like to return a new array of objects of only those marked activie: true like so:

[
    { id: 1, active: true },
    { id: 3, active: true }
  ]

I know I need an empty array to add the objects too (i think?), loop through the object, and filter out the correct items and return them, however i am having a bit of an issue on how to go about writing this. If anyone could help me out, would really appreciate it.

Cheers

There is a filter function for arrays, which works like this

array.filter(function (element) {
    return <true condition>
});

Where you use the element to forge the condition of when you want to retrive the current element.

Good luck :slight_smile:

Is this all the code I would need? Or is there just a piece of the puzzle? Thanks for the tip!!

It’s just a piece of the puzzle indeed ! :stuck_out_tongue: You need to figure out how to use the function and what condition to put at the return.

Also, I didn’t mention it but the function filter returns a new array containing the matching elements so you can store the result :wink:

oh boy! alright i’ll give it a shot. Thanks so much for the help

I don’t think im using my function correctly?

const list = [
  { id: 1, active: true },
  { id: 2, active: false },
  { id: 3, active: true  },
  { id: 4, active: false }
];

function selectActive(list) {
  var result = list.filter(function(obj) {
    return obj.active === true; 
  }) 
}

(selectActive(list)

This would work if I didnt have a function, and just used my variable, but I am trying to do it in this function. Any direction is greatly appreciated

In your function you’re going to want to return the result.
And also,
(selectActive(list)

get rid of that opening parentheses
-> selectActive(list)

1 Like

ahhh, i stored what I wanted in my result but never returned my result.

1 Like