I want to check if there is a value in the array which has more than 10 difference with other values:
console.log(check());
function check() {
const array = [21, 21, 10];
return array.some((val, i, arr) => val > arr[0] + 10);
}
The above array should return true because there is at least one value in the array which has more than 10 difference, But as you see it returns false!!
How can I do this?
You could take the max and min value and check the difference.
function check(array) {
return Math.max(...array) - Math.min(...array) > 10;
}
console.log(check([21, 21, 10]));
You are checking if any of the array items are bigger than the first item + 10, which is not true.
You can check every element with the minimum element though:
console.log(check());
function check() {
const array = [21, 21, 10];
const min = Math.min(...array);
return array.some(val => val > min + 10);
}