Check if Javascript array values are in ascending order
One other very nice functional way of doing this could be;
var isAscending = a => a.slice(1)
.map((e,i) => e > a[i])
.every(x => x);
console.log(isAscending([1,2,3,4]));
console.log(isAscending([1,2,5,4]));
Nice code but there are redundancies in it. We can further simplify by consolidating .map()
and .every()
into one.
var isAscending = a => a.slice(1)
.every((e,i) => e > a[i]);
console.log(isAscending([1,2,3,4]));
console.log(isAscending([1,2,5,4]));
Keep track of the largest value you have seen (see the fiddle):
function find_invalid_numbers(arr) {
var nonvalid, i, max;
nonvalid = [];
if (arr.length !== 0) {
max = arr[0];
for (i = 1; i < arr.length; ++i) {
if (arr[i] < max) {
nonvalid.push(arr[i]);
} else {
max = arr[i];
}
}
}
return nonvalid;
}