Using array map to filter results with if conditional

Related searches

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!

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.

Simplify your JavaScript – Use .map(), .reduce(), and .filter(), If you're starting in JavaScript, maybe you haven't heard of .map() the result of this callback (the accumulator) from one array element to the� Filter The filter () method takes each element in an array and it applies a conditional statement against it. If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.

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)

Can we use map function instead of filter function?, result with map if i use conditional statements instead of filter function If you want to get the elements of your array that satisfy some criteria,� If you’re starting in JavaScript, maybe you haven’t heard of .map(), .reduce(), and .filter().For me, it took a while as I had to support Internet Explorer 8 until a couple years ago.

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

JavaScript Map, Reduce, and Filter, Map, reduce, and filter are all array methods in JavaScript. If this conditional returns true, the element gets pushed to the output array. If the� That filter function will loop through every object in the people array and check the value of age inside each object to check if it is less than 60. If it is, then we include it in the next step, which is to map those filtered objects out. Let’s see the entire React component that filters an array of objects by a value inside of the object:

How to Use Map, Filter, & Reduce in JavaScript, Typical examples of this are squaring every element in an array of array. If you run this in your console, you'll get the same result as before. The map() method creates a new array with the results of calling a function for every array element. The map() method calls the provided function once for each element in an array, in order. Note: map() does not execute the function for array elements without values. Note: this method does not change the original array.

JavaScript Array Filter: Filtering Array Elements Based on a Test , This tutorial shows you how to use the JavaScript array filter method to filter elements in an array based on a specified condition. The filter() method includes only the element in the result array if the element satisfies the test in Like other iterative methods of the Array object such as every(), some(), map() and forEach(),� Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example:. Given an array of strings, you could go over every string & make every character UPPERCASE.

The FILTER function filters list1 using the values provided by COUNTIF. Values associated with zero are removed; other values are preserved. The final result is an array of values that exist in both lists, which spills into the range F5:F11. Extended logic. In the above formula, we use the raw results from COUNTIF as the filter.

Comments
  • In JS there's Array.prototype.filter method for this purpose.
  • Can I then turn appids into an arra of just ids and not the full object? thanks for your help!
  • @user3201696 You would need to chain a .map() after the filter, definitely possible.
  • @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?
  • @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 oh this is exactly what I'm looking for, thank you so much!!
  • @DanMandel is possible to stop pushing element first time pushed.. i meant only one value should printed on console..?
  • @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"
  • @JustinL. Thanks for the reply and i solved this form another Stack overflow question....
  • @DanMandel - How can filter + map be O(n^2) ? It will be O(2n) I think, which is basically O(n)
  • @DanMandel filter + map is definitely O(n) not n².