Home > Blockchain >  Return all objects within an array based on if they contain a portion of a string
Return all objects within an array based on if they contain a portion of a string

Time:12-03

[
  {
    "population": 121321313,
    "location": "American city in the East"
  },
  {
    "population": 54646546,
    "location": "Canadian city in the East"
  },
  {
    "population": 6546467,
    "location": "American city in the West"
  },
  {
    "population": 145313,
    "location": "American city in the South"
  },
  {
    "population": 12673,
    "location": "Canadian city2 in the East"
  },
  {
    "population": 141313,
    "location": "Canadian city in the South"
  },
  {
    "population": 1264473,
    "location": "Canadian city4 in the East"
  },
  {
    "population": 12673,
    "location": "Canadian city6 in the South"
  }
  
]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I'm trying to figure out how to filter out all the objects within the array based on whether their location is American or Canadian and by Region (East, West, South).

For example, if I want all Canadian cities in the East it would return objects with the index of 1,4,6. How would you filter out the location string within the array based on two parameters, whether they contain American or Candian and East, West, South.

CodePudding user response:

Hopefully the following example will put you on the right track

Assumption: your array is stored in a variable named data

var searchString = "American";
var filteredData = data.filter((item) => {
    return item.location.includes(searchString);
});
for (var i = 0; i < filteredData.length; i  ) {
    console.log(filteredData[i].location);
}

Fabio

  • Related