There is a array like this on my hand;
var array = [{value:"0"},{value:"1"},{value:"2"},{value:"3"},{value:"4"}];
I need check, this numbers is going consecutive?
[{value:"0"},{value:"1"},{value:"2"},{value:"3"},{value:"4"}]; TRUE (0,1,2,3,4) [{value:"0"},{value:"1"},{value:"2"},{value:"3"},{value:"5"}]; FALSE (0,1,2,3,5)
Advertisement
Answer
You can use reduce with the initial value as the first element of the array
const checkIsConsecutive = (array) => Boolean(array.reduce((res, cur) => (res ? (Number(res.value) + 1 === Number(cur.value) ? cur : false) : false))); console.log(checkIsConsecutive([{ value: '0' }, { value: '1' }, { value: '2' }, { value: '3' }, { value: '4' }])); console.log(checkIsConsecutive([{ value: '0' }, { value: '1' }, { value: '2' }, { value: '3' }, { value: '5' }]));