dimanche 19 avril 2015

Javascript:: Validate duplicate(d) value(s) within array that contains key(s)

Before I will explain what my goal is let me start with my code:



var arr=['Hezi','Gangina','HeziGangina','Hezi-Gangina'];

function iUnique(v,i,s)
{
return s.indexOf(v)===i;
}

if(arr.length!==arr.filter(iUnique).length)
{

var arrayDup=
arr.filter(iUnique).filter
(
function(item,index)
{
return arr.indexOf(item)!==arr.lastIndexOf(item)
}
);

var dupVal=arrayDup.length;
throw new Error("Opps! Duplicate"+(dupVal>1?"d":"")+" value"+(dupVal>1?"s":"")+" : "+arrayDup);

}

arr.forEach(function(e)
{
document.writeln(e+"<br>");
});

arr=[];


Now,


Up until this point everything is working perfectly (no need to touch)...


BUT


I want to be able to append keys to my current array.


The array keys will be duplicated so there is no reason to validate duplicated values to the array keys.


IOW... I expect that :



var arr=[A:'Hezi',A:'Gangina',A:'HeziGangina',B:'Hezi-Gangina']; // This would NOT throw a new error.
var arr=[A:'Hezi',A:'Gangina',A:'HeziGangina',B:'Hezi']; // This WOULD throw a new error.


Here is the JSFiddle (I changed document.writeln to console.log):


http://ift.tt/1DzjPBK


So basically my goal is to keep the exact same proper functionality of my current code but at the same time I to be able to append keys to my current array.


I need fresh brain to take a look at this :)


Aucun commentaire:

Enregistrer un commentaire