0

I have two arrays in my demo application. Array one has countries with content another one is list countries. So, i want to remove countries from array one, if that country not contained in country array. I have put my array values below,

var continent = [
    {
        "continent":"Europe",
        "country":["Albania", "Andorra", "UK", "Ireland"]
    },
    {
        "continent":"Asia",
        "country":["Armenia", "Cambodia", "China", "Cyprus"]
    }
]

var selectedCountries = ["Albania", "Andorra", "Armenia"];

The output

var result = [
    {
        "continent":"Europe",
        "country":["Albania", "Andorra"]
    },
    {
        "continent":"Asia",
        "country":["Armenia"]
    }
]
taile
  • 2,738
  • 17
  • 29
Sathya
  • 1,704
  • 3
  • 36
  • 58
  • Possible duplicate of [For-each over an array in JavaScript?](http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) – nyedidikeke May 06 '17 at 11:14

2 Answers2

1
output=continent.map(continent=>{
    return {
        country:continent.country.filter(country=>selectedCountries.find(c=>c===country)),
         continent:continent.continent
    };
 });

Simply filter the countrys by the selectCountries array...

http://jsbin.com/lagonukuni/edit?console

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

If you are looking at modifying original array, you can do this:

forEach and `filter` would do the job.
  1. Just iterate over continent array.
  2. For each object that contains country array, keep the ones that are present in the selectedCountries collection.

var continent = [
    {
        "continent":"Europe",
        "country":["Albania", "Andorra", "UK", "Ireland"]
    },
    {
        "continent":"Asia",
        "country":["Armenia", "Cambodia", "China", "Cyprus"]
    }
];

var selectedCountries = ["Albania", "Andorra", "Armenia"];

continent.forEach(function (c,i) {
  c.country = c.country.filter(function (v,i) {
    return selectedCountries.includes(v);
  });
});
console.log(continent);
Pankaj Shukla
  • 2,657
  • 2
  • 11
  • 18