1

I have a function that takes two lists(each item in the two lists are the same type). It only adds item from the second list to the first list if the item in the second list does not exist in the first list. To determine if it exist in the list, I compare the property pk.

addUniqueItemsToList: function (sourceList, toAddList) {
    for (var a = 0; a < toAddList.length; a++) {
        var doesItemExist = false;
        for (var b = 0; b < sourceList.length; b++) {
            if (sourceList[b].pk == toAddList[a].pk) {
                doesItemExist = true;
                break;
            }
        }

        if (!doesItemExist) {
            sourceList.push(toAddList[a]);
        }
    }
}

Is there a way in javascript where instead of comparing pk, I can compare it to other properties of the object, by passing in the name of the property to the function? i.e., addUniqueItemsToList: function (sourceList, toAddList, propertyName)

3
  • Surely you could use the alternative method object[propertyName]? Commented Jun 8, 2015 at 16:52
  • Great, I didn't think of using that! Thanks Commented Jun 8, 2015 at 17:05
  • also you can create a map by property of one of the two set of items in order to avoid a 1->n for. It would be 1 or 2 fors for create the map, and one for to validate that one value exist in another value so if you have 100 items in set one and 200 items in set two, yo have not 2000 iterations but 100 or 200. Commented Jun 8, 2015 at 17:19

1 Answer 1

1

Yes you can compare by object property directly and access properties dinamically using string as key ej array['mykey']. Also it would be better if instead of doing a for inside a for (1for - n for) create a map in order to avoid so much iterations:

Eg: Number iterations without a map when items.length = 100 & anotherItems.length = 200

100*200 = 20000 possibles iterations.

Eg. Number of iterations creating a map with items.length = 100 & anotherItems.length = 200

300 iterations.

Example of how i do it:

var items = [{_id: 1, text: "Text 1"}, {_id:2, text: "Text 2"}];
var anotherItems = [{_id: 1, text: "Text 1"}];

var mapByProperty = function(array, prop) {
    var map = [];
    for (var i = 0, len = array.length; i !== len; i++) {
        map[array[i][prop]] = array[i];
    }
    return map;
};
var commonUniqueProperty = '_id';
var mappedAnotherItemsById = mapByProperty(anotherItems, commonUniqueProperty);

for(var i = 0, len = items.length; i !== len; i++) {
   if(mappedAnotherItemsById[items[i][commonUniqueProperty]]) {
        console.log(items[i]);
   }
}
Sign up to request clarification or add additional context in comments.

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.