Raffy T Lawrence Raffy T Lawrence - 2 months ago 6
Javascript Question

Javascript : Validating array sequence value except the zero 0

I have an array validating if values are ordered by descending or not. However, if the sequence have a value of 0 it interrupt the process and returns false instead of true. How do i avoid the 0 value and continue the process as descending. https://jsfiddle.net/snb3p0qy/1/

function customValidate(array) {
var length = array.length;
return array.every(function(value, index) {
var nextIndex = index + 1;
return nextIndex < length ? value >= array[nextIndex] : true;
});
}
document.write(customValidate([1, 2, 3, 4, 5]));
document.write(customValidate([5, 0, 3, 2, 1]));//This supposed to be true
document.write(customValidate([0, 0, 0, 4, 5]));
document.write(customValidate([0, 0, 0, 2, 1]));

Answer

try the following return statement

return nextIndex < length ? value === 0 || value >= array[nextIndex] : true;

or even

return nextIndex >= length || value === 0 || value >= array[nextIndex];

so I edited the code just to make it work for [ 5 , 0 , 1 ] scenario but of course it will be much better to use a for loop like the second answer.

while (array[nextIndex] === 0 && nextIndex < length) {
    nextIndex++;
}
return nextIndex >= length || value === 0 || value >= array[nextIndex];
Comments