Click here to Skip to main content
15,895,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to get the non recurring[not duplicate] value from a String Array in javascript

For eg:

if the String Array
A=[850,851,850]

then,i need the o/p as:
851
Posted

OK, there is an easier way, using indexof

http://www.w3schools.com/jsref/jsref_indexof_array.asp[^]



var i = 0;

for(i; i < arr.length;++i)
{
  if (arr.indexOf(arr[i])) == arr.lastIndexOf(arr[i]))
   {
     // This means it's only in there once.
   }
}
 
Share this answer
 
v2
Comments
Karthik_Mahalingam 23-Jan-14 4:54am    
5
fiashieen 23-Jan-14 5:42am    
yaa....you are right Karthik it was my mistake.This one really works for larger data's...Thank you so much n sorry Christian
try this..


JavaScript
var A = [850, 851, 850];
            var output = new Array();
            for (var i = 0; i < A.length; i++) {
                var current = A[i];
                var flag = 0;
                for (var j = 0; j < A.length; j++) {
                    if (current == A[j])
                        flag++;
                }
                if (flag == 1)
                    output.push(current);
            }

            alert(output);
 
Share this answer
 
v2
Comments
fiashieen 23-Jan-14 4:34am    
Thanks a lot...:)
Christian Graus 23-Jan-14 4:41am    
*sigh* This is very inefficient. My solution is much neater.
Karthik_Mahalingam 23-Jan-14 4:52am    
Yes Christian, Due to inner loop i guess ..


Christian Graus 23-Jan-14 4:55am    
Yes, that's right. It also does not run, 'out.push. should be 'output.push'
Karthik_Mahalingam 23-Jan-14 4:57am    
yes, i changed later :)
That looks an array of numbers, to me.
Anyway you could, iterating on the items of the array, use the IndexOf method to check if it has a duplicate, stopping your iteration at first non-duplicate detection.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900