0

I would like to parse it and find if two value exist only once within this array.

Example: "text-success" OR "muted" if EXIST ONCE return the array

if it EXIST twice retrun null

example:

Array[6]
0:"text-warning"
1:"text-success"
2:"text-warning"
3:"text-success"
4:"muted"
5:"text-warning"
Array[6]
0:"text-warning"
1:"text-warning"
2:"text-warning"
3:"text-warning"
4:"text-success"
5:"text-warning"
Array[6]
0:"text-warning"
1:"text-warning"
2:"text-warning"
3:"text-success"
4:"muted"
5:"text-warning"
Array[6]
0:"text-warning"
1:"text-warning"
2:"text-warning"
3:"text-warning"
4:"muted"
5:"text-warning"

1st one will return FALSE because both exist "text-success"-twice AND "muted"-once

2nd one will return TRUE because it exist ONCE "text-success"

3rd one will return FALSE because both exist "text-success" AND "muted"

4th one will return TRUE because it exist ONCE "muted"

. . . .

and so on

so far this is my Javascript:

function singles( array ) {
 for( var index = 0, single = []; index < array.length; index++ ) {
 if( array.indexOf( array[index], array.indexOf( array[index] ) + 1 ) == -1 ) single.push( array[index] ); 
 };
 return single;
};

it is not working

please help.

asked Jul 21, 2016 at 11:04
0

1 Answer 1

2

You could use a simple loop with a counter as follows :

var count = 0;
for(i=0;i<arr.length;i++) {
if(arr[i] == "test-success" || arr[i] == "muted") {
count++;
}
if(count == 1) {
//process array data;
}
answered Jul 21, 2016 at 11:14
Sign up to request clarification or add additional context in comments.

4 Comments

the code looks cool, but what if Both "test-success" and "muted" exist then it should not count
In the 3rd example above muted and success exits once each and the result is false, in this case count will be 2 and thus result false. Only if either muted or success exist once only will it be true. Is this not the case?
var count = 0; for( var index = 0, single = []; index < array.length; index++ ) { if(array[index] == "test-success" || array[index] == "muted") { count++; } if(count == 1) { single.push(array[index]); } } return single;
the if(count == 1) needs to be outside the for loop.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.