1

How can i check an array if its elements are all 0's except one which is 1?

sample:

array = [0, 0, 0, 1, 0];
check(array); //returns the index where it is 1 which is 3

array = [0, 3, 0, 2, 0];
check(array); //returns -1

array = [0, 3, 1, 2, 0];
check(array); //returns -1 again if there are non zero aside from 1, it should be one 1 and others are all 0.

array = [0, 0, 1, 0, 1];
check(array); //returns -1 again, there should just be one element of 1

3 Answers 3

1
function check(a) {
    var index = -1;
    for (var i = 0; i < a.length; i++) {
        if (a[i] == 1) {
            if (index < 0) {
                index = i;
            } else {
                return -1;
            }
        } else if (a[i] != 0) {
            return -1;
        }
    }
    return index;
}

array1 = [0, 0, 0, 1, 0];
check(array1); //returns 3

array2 = [0, 3, 0, 2, 0];
check(array2); //returns -1
Sign up to request clarification or add additional context in comments.

5 Comments

Nice.. thanks Colin :) good answer. this is the function i wanted precisely.
I think you meant else if (a[i] != 0) instead of else if (a[1] != 0), right? Or am I missing something? Otherwise an array like array1 = [0, 1, 0, 0, 0]; would return -1
@Tico Whoops. I fixed it.
@Enzo There was a typo in there. You should look at the new version.
@ColinvH Phew! It's almost 4am, I thought I was losing something. Nice answer :)
0

You can use a couple of filters, to generate an array of invalid numbers (i.e. not 0 or 1), and then an array of ones - from the original array. In the end, you can check the lengths of these resultant arrays to see if your criteria is met.

var others = a.filter(function(_item) { return (_item !== 1 && _item !== 0); }),
    ones = a.filter(function(_item) { return (_item === 1); });

if(others.length === 0 && ones.length === 1) {
    // valid
}

1 Comment

This doesn't return the index where the single one occurred as the OP wanted.
0

If array elements are guaranteed to be non-negative , then you can sum all elements of array. If sum is anything other than 1, it is not your desired array. You don't have to loop array elements to calculate sum of elements. Use new reduce function of JavaScript Array. Look it up on web.

Things can get complicated , if array elements can be negative as well.

1 Comment

Looping and reducing are both O(n). May as well use a solution that works in every case instead of just one, especially if it's the same efficiency.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.