I'm trying to use .every of Array to see if items in the array are sequential (1, 2, 3, 4, 5). Why does this return false when everything in it is true?
const nums = [1, 2, 3, 4, 5];
nums.every((num, index) => {
if (index !== nums.length - 1) {
console.log(num + 1 === nums[index + 1]);
return num + 1 === nums[index + 1];
}
});
You're not returning anything on the last iteration, so the return value is undefined, which is falsey, so the .every will fail - return true in an else:
const nums = [1, 2, 3, 4, 5];
console.log(
nums.every((num, index) => {
if (index !== nums.length - 1) {
console.log(num + 1 === nums[index + 1]);
return num + 1 === nums[index + 1];
} else {
return true;
}
})
);
Or, without the console.log:
const nums = [1, 2, 3, 4, 5];
console.log(
nums.every((num, index) => (
index !== nums.length - 1
? num + 1 === nums[index + 1]
: true
))
);
I would return true for the first element and then check the last item against the actual one.
Why the first element? It is easier to check. Compare
!index
vs
index !== array.length - 1
As you see the first check is shorter, compared to the second one.
const
nums = [1, 2, 3, 4, 5],
isInOrder = nums.every((num, index, array) => {
if (!index) return true;
return array[index - 1] + 1 === num;
});
console.log(isInOrder);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With