-1

I have an object with accounts, example:

    {
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }

Let's say I want to filter out only the objects with the states of "FL" and "OH", how could I use the filter() to do that? Thanks.

Colin Sygiel
  • 917
  • 6
  • 18
  • 29

3 Answers3

3

Try this

function filterArray (item) {
    if (item.state === "OH" || item.state === "FL"){
        return item;
    }
}

var resultArray = yourArray.filter(filterArray);
console.log(resultArray);
forJ
  • 4,309
  • 6
  • 34
  • 60
1

Try this:

var array = [{
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }];
    
    var filterArray = array.filter(function(item){
      return item.state === 'FL' || item.state === 'OH';
    });
    
    console.log(filterArray);
Matej Marconak
  • 1,365
  • 3
  • 20
  • 25
0

use array.filter(callback) which takes a function with one argument and return the value that meets the condition you want :

var testArray = [ {
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }];
  var filtered = testArray.filter(isStateFLorOH);

and the fucntion callback should be like this :

function isStateFLorOH(value){

if(value.state == "FL" || value.satate == "OH")
return value;
}
Ali Ezzat Odeh
  • 2,093
  • 1
  • 17
  • 17