2

I have a main array of tags

var tagsArray = [
    {
        name: "1",
        selected: undefined
    },
    {
        name: "2",
        selected: undefined
    },
    {
        name: "3",
        selected: undefined
    }
]

Then an array of selected tags to compare it to:

var selectedTags = [
    {
        name: "1",
        selected: true
    }
]

How would you run some kind of comparison (for-loop) to check what objects in selectedTags have the selected: true value?

Then also set the same object's selected value in tagsArray to true?

Leon Gaban
  • 36,509
  • 115
  • 332
  • 529

2 Answers2

1

Create an access map, then iterate and find the true values and set the values in the other array

var map = {};

tagsArray.forEach(function(obj, index) {
    map[obj.name] = index;
});

selectedTags.forEach(function(obj) {
    if ( obj.selected ) {
        tagsArray[map[obj.name]].selected = true;
    }
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

You can still use 2 for-loops and it doesn't look much worse in terms of code or clarity. But on average it will run slower O(n^2) than using map.

var i,j;

for(i = 0; i < tagsArray.length; i++){
    for(j = 0; j < selectedTags.length; j++){
        if(tagsArray[i].name === selectedTags[j].name){
            tagsArray[i].selected = true;
            break;
        }
    }
}

JS Fiddle

ztyankov
  • 21
  • 1
  • Thanks for the tip! I guess the `map` works the same way as a `switch-case` statement, in that it finds what it needs to find faster? – Leon Gaban Apr 29 '15 at 19:48
  • 1
    You're welcome! Maps are designed for fast data look up. So for example, instead of doing the whole inside loop to match a name from tagsArray to selectedTags array, it uses a different approach that uses less time to find the same match. – ztyankov Apr 29 '15 at 19:57