Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to find minimum distance between two numbers in an array with JavaScript

1 Answer

0 votes
function MinDistance(arr, number1, number2) {
    const size = arr.length;
    let min_distance = Number.MAX_VALUE;
    
    for (let i = 0; i < size; i++) {
        for (let j = i + 1; j < size; j++) {
            if (arr[i] == number1 && arr[j] == number2 || 
                arr[i] == number2 && arr[j] == number1) {
                min_distance = Math.min(min_distance, Math.abs(i - j));
            }
        }
    }
    return min_distance;
}
        
const arr = [2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3];
        
console.log(MinDistance(arr, 3, 8));




/*
run:

2

*/

 



answered Aug 24, 2022 by avibootz

Related questions

...