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"]
    }
]
1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.