Reputation: 1237
I'm having a bad coding day. I simply don't get why this code on fiddle is not doing what I expect it to.
var masterList = new Array();
var templates = new Array();
templates.push({"name":"name 1", "value":"1234"});
templates.push({"name":"name 2", "value":"2345"});
templates.push({"name":"name 3", "value":"3456"});
templates.push({"name":"name 4", "value":"4567"});
templates.push({"name":"name 1", "value":"5678"});
templates.push({"name":"name 2", "value":"6789"});
templates.push({"name":"name 3", "value":"7890"});
templates.push({"name":"name 4", "value":"8901"});
var addUnique = function(thatObj) {
var newList = new Array();
if ( masterList.length == 0 ) {
// add the first element and return
masterList.push(thatObj);
return;
}
for (j=0; j<masterList.length; j++) {
if (masterList[j].name != thatObj.name) {
newList.push(thatObj);
}
}
// store the new master list
masterList = newList.splice(0);
}
for (i=0; i<8; i++) {
addUnique(templates[i]);
}
console.log(masterList);
console.log(masterList.length);
In my (humble) opinion it should go through the templates array, fill the masterList with each element of the templateArray, but only result in 4 elements in the master array, as the ones that are named the same should be "overwritten", i.e. not copied into the intermediate array and thus not carried on and replaced with the new. Instead, I get one single entry in masterList.
Where have the good old days gone, strongly typed languages. Pointers. Sigh. I just dont' get what sort of mess javascript is making (well, I am making the mess of course) but I blame JS for not understanding me...
Upvotes: 0
Views: 97
Reputation: 46647
newList
is scoped to the addUnique
function, which you call 8 times in a loop. each time this function runs, you assign a new value to masterList (masterList = newList.splice(0);
) so only the last value is showing up in the console.log(masterList)
.
Here is a fixed version of your fiddle: http://jsfiddle.net/vZNKb/2/
var addUnique = function(thatObj) {
if ( masterList.length == 0 ) {
// add the first element and return
masterList.push(thatObj);
return;
}
var exists = false;
for (var j = 0; j < masterList.length; j++) {
if (masterList[j].name == thatObj.name) {
exists = true;
break;
}
}
if (!exists) {
masterList.push(thatObj);
}
}
Upvotes: 2
Reputation: 5929
your loop in addUnique
needs to loop over ALL the elements first...then add if none of the elements match
relevant section
var matchingRecord = false;
for(j=0;j<masterList.length;j++) {
if (masterList[j].name == thatObj.name){
matchingRecord = true;
break;
}
}
if(!matchingRecord) newList.push(thatObj);
Upvotes: 0