Dimitar
Dimitar

Reputation: 1928

Find out in an array of numbers if any number is close to any of the numbers in the array

I have array of different whole numbers like so [46, 18, 49, 15] what i want to know if there is any number that is close to any of the other numbers in this case there aren't any so the function have to return false, but if there are for example [14, 31, 13, 40, 30] 30 and 31 are close and 14 and 13 to each others so the function have to return true. thanks!

Upvotes: 1

Views: 80

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386530

Just sort it and check the delta.

function close(a) {
    a.sort(function (a, b) { return a - b; });
    return a.some(function (b, i, aa) {
        return i && b - aa[i - 1] <= 1;
    });
}

document.write(close([14, 31, 13, 40, 30])+'<br>');
document.write(close([46, 18, 49, 15]) + '<br>');

Upvotes: 2

Luka
Luka

Reputation: 3089

Sort the numbers. Then loop through the numbers and for each number see if this number is equal to the next number minus 1. If that is true, return true. Otherwise, if you finished the loop, return false.

Upvotes: 4

Related Questions