简体   繁体   中英

Remove all items of an array if they exist in another array

I have a array in which I add different categories of items from other arrays:

For example, 2 arrays countries and languages:

countries = ['US', 'UK', 'Canada'];
languages = ['English', 'French', 'German'];

Which I use to populate another array:

items = ['US', 'French'];

In items I can only have one item from countries and languages so each time I want to add a country in items I have to remove the other country which was already in items.

For now the way I am doing it is looping through countries and languages to check if the item is in items but I am sure there is a more elegant way to do it, using underscore.js for example:

for ( var i = 0; i < country.length; i ++){
  if (items.indexOf(country[i]) > -1){
       items.splice($.inArray(country[i], items),1)
  }
}

Does anyone have a simple solution?

Best

Not sure if I understand completely. Why don't you use object instead of array?

var items = {'country': 'US', 'language': 'English'};

Then, when you add another country to items by assigning items.country = 'UK'; the previous country would be overwritten, thus you would always end up with only one item from countries and one item from languages in items object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM