Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using .every to check if items in array are sequential

Tags:

javascript

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];
  }
});
like image 515
totalnoob Avatar asked Mar 13 '26 03:03

totalnoob


2 Answers

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
  ))
);
like image 56
CertainPerformance Avatar answered Mar 14 '26 15:03

CertainPerformance


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);
like image 24
Nina Scholz Avatar answered Mar 14 '26 17:03

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!