简体   繁体   中英

Javascript check on array's elements

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
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

You can use a couple of filters, to generate an array of invalid numbers (ie 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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM