95

I am trying to use an array map to filter a object a bit further to prepare it to send to the server to for saving. I can filter to 1 key value, which is great, but I want to take it 1 step further and check them against a boolean inside.

So, right now this is what I have -

$scope.appIds = $scope.applicationsHere.map( function(obj){
        if(obj.selected == true){
            return obj.id;
        }
    });

This works great for pulling out the id's, however I don't want to push them in this new array if they their selected value == false, so I put a conditional to filter further. This somewhat works, I get an array of id's, but the id's that have .selected == false are still in the array, just with the value of null. So If I have 4 items in the object and 2 of them are false it looks like this -

 appIds = {id1, id2, null, null};

My question is - is there a way to do this without the nulls being put in there. Thanks for reading!

1
  • 2
    In JS there's Array.prototype.filter method for this purpose.
    – pawel
    Nov 3, 2014 at 14:59

5 Answers 5

156

You're looking for the .filter() function:

  $scope.appIds = $scope.applicationsHere.filter(function(obj) {
    return obj.selected;
  });

That'll produce an array that contains only those objects whose "selected" property is true (or truthy).

edit sorry I was getting some coffee and I missed the comments - yes, as jAndy noted in a comment, to filter and then pluck out just the "id" values, it'd be:

  $scope.appIds = $scope.applicationsHere.filter(function(obj) {
    return obj.selected;
  }).map(function(obj) { return obj.id; });

Some functional libraries (like Functional, which in my opinion doesn't get enough love) have a .pluck() function to extract property values from a list of objects, but native JavaScript has a pretty lean set of such tools.

7
  • 1
    Can I then turn appids into an arra of just ids and not the full object? thanks for your help!
    – ajmajmajma
    Nov 3, 2014 at 15:00
  • 5
    @user3201696 You would need to chain a .map() after the filter, definitely possible.
    – jAndy
    Nov 3, 2014 at 15:01
  • @jAndy awesome, thanks!! Is there somewhere I can see an example, as I'm sure how to chain the 2 together. Would I just do the map inside this filter after the return?
    – ajmajmajma
    Nov 3, 2014 at 15:02
  • 2
    @user3201696 it would pretty much look like .filter(function(obj) { return obj.selected; }).map(function(obj) { return obj.id1 }); That would create a new array which only contains the values of the id1 properties.
    – jAndy
    Nov 3, 2014 at 15:04
  • Great answers, thank you for your help guys. Quick follow up question, can you use these methods to do the reverse of this. So when I get the array back can these methods be used to compare the id array to the object to set the .selected on the object to true (they are all false be default when landing)? My initial idea is to double loop and compare the ids to the ids in the object, but I don't think it is the best method. Thanks again!
    – ajmajmajma
    Nov 3, 2014 at 15:23
34

You should use Array.prototype.reduce to do this. I did do a little JS perf test to verify that this is more performant than doing a .filter + .map.

$scope.appIds = $scope.applicationsHere.reduce(function(ids, obj){
    if(obj.selected === true){
        ids.push(obj.id);
    }
    return ids;
}, []);

Just for the sake of clarity, here's the sample .reduce I used in the JSPerf test:

  var things = [
    {id: 1, selected: true},
    {id: 2, selected: true},
    {id: 3, selected: true},
    {id: 4, selected: true},
    {id: 5, selected: false},
    {id: 6, selected: true},
    {id: 7, selected: false},
    {id: 8, selected: true},
    {id: 9, selected: false},
    {id: 10, selected: true},
  ];
  
  	
var ids = things.reduce((ids, thing) => {
  if (thing.selected) {
    ids.push(thing.id);
  }
  return ids;
}, []);

console.log(ids)


EDIT 1

Note, As of 2/2018 Reduce + Push is fastest in Chrome and Edge, but slower than Filter + Map in Firefox

6
  • @DanMandel is possible to stop pushing element first time pushed.. i meant only one value should printed on console..? Aug 13, 2019 at 10:17
  • 1
    @SivaprakashD do you mean you want to find the first instance where this is true? you could var id = things.find(thing => thing.selected) and it would stop after it finds the first instance developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. Or use similar .some method to just get a true/false "does this object live in this array"
    – Justin L.
    Aug 14, 2019 at 20:37
  • @JustinL. Thanks for the reply and i solved this form another Stack overflow question.... Aug 18, 2019 at 13:27
  • 2
    @DanMandel - How can filter + map be O(n^2) ? It will be O(2n) I think, which is basically O(n)
    – Vatsal
    Jun 10, 2020 at 23:49
  • 2
    @DanMandel filter + map is definitely O(n) not n².
    – callback
    Aug 10, 2020 at 21:08
21

You could use flatMap. It can filter and map in one.

$scope.appIds = $scope.applicationsHere.flatMap(obj => obj.selected ? obj.id : [])
6

Simple solution

SomeArrayValues.filter(x=> x.id !== idNameDetailsColorDto.id).map(ids => (ids.id))
4

Here's some info if someone comes upon this in 2019.

I think reduce vs map + filter might be somewhat dependent on what you need to loop through. Not sure on this but reduce does seem to be slower.

One thing is for sure - if you're looking for performance improvements the way you write the code is extremely important!

Here a JS perf test that shows the massive improvements when typing out the code fully rather than checking for "falsey" values (e.g. if (string) {...}) or returning "falsey" values where a boolean is expected.

Hope this helps someone

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.