I have an array of four numbers, something like [597103978, 564784412, 590236070, 170889704]
and I need to make sure that the variance is no more than 10%, for example for the array above, the check must fail because of the number 170889704.
Can someone suggest me a good method how to do that is Javascript?
Thanks in advance!
I would do it using Array.every
const arr = [597103978, 564784412, 590236070, 170889704];
const variance = (n, m) => {
return Math.abs( (n - m) / n );
};
const isLessThanTenPercent = (n) => {
return ( n < 0.1 );
};
const arrayIsGood = arr.every((n, i) => {
// m is the next element after n
const m = arr[i+1];
if (Number.isInteger(m)) {
const v = variance(n, m);
return isLessThanTenPercent(v);
} else {
// if m is not an integer, we're at the last element
return true;
}
});
console.log({arrayIsGood});