1

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

apxcode
  • 7,696
  • 7
  • 30
  • 41
Spearfisher
  • 8,445
  • 19
  • 70
  • 124

1 Answers1

2

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.

Bugs Bunny
  • 2,496
  • 1
  • 26
  • 32