This tutorial will demonstrate how to find unique values in any given array and also how the elements return are in the same position as they were in the original subject array, i.e. only duplicates are removed, this is very important that the elements remain in their order but not shuffled, the code is fairly simple it takes an array from which we have to find unique values and make a new buffer array which holds all the unique values, once all the subject array is traverse buffer array will be returned back.
now let the code talk
now let the code talk
function uniqueArray(subjectArray){ k=subjectArray.length; if(k<=1){ // if array length is 1 or 0 // just return it, because it // is already unique return subjectArray; } buffer=new Array(); c=0; for(var i=0;i<k;i++){ if(!isRepeated(buffer,subjectArray[i])){ buffer[c++]=subjectArray[i]; } } return buffer; } // function to check is the subject element // is present in buffer array or not function isRepeated(bufferArray,checkValue){ for(var i=0;i<bufferArray.length;i++){ if(bufferArray[i]==checkValue){ return true; } } return false; }
Example
subjectArray=new Array(); subjectArray[0]=1; subjectArray[1]=2; subjectArray[2]=1; subjectArray[3]=3; subjectArray[4]=1; subjectArray[5]="one"; subjectArray[6]="two"; subjectArray[7]="one"; alert (uniqueArray(subjectArray));Output:1,2,3,one,two
0 comments:
Post a Comment