skip to Main Content

How to test a pair of numbers in one array?

like

const arr = [1, 3, 5, 9, 11, 12]

I want to test 1 and 3, 3 and 5, 5 and 9, 9 and 11, 11 and 12.

for (let i= 0; arr.length > i; i++){
  for (let j=0; arr.length > j; j++){
        console.log(arr[i], arr[j])


}}

How does the douple for loop needs to look like in javascript.

3

Answers


  1. As mentioned by @gog, you can achieve the pair testing in an array with a single loop. Just iterate from 0 to length – 2 and compare arr[i] with arr[i+1].

    To do this, use the loop condition i < arr.length – 1. This approach ensures you stop just before the last element, allowing for valid pair comparisons between adjacent elements.

    Login or Signup to reply.
  2. Quite simply using a "sliding window" technique:

    for(let i = 0, max = arr.length - 1; i < max; i += 1) {
      const first = arr[i];
      const second = arr[i + 1];
    
      // do something with first and second
    }
    

    You can even generalize it:

    function slidingWindow(size, callback) {
      const lengthOffset = size - 1;
      for(let i = 0, max = arr.length - lengthOffset; i < max; i += 1){
        const slide = arr.slice(i, i + size);
        callback(slide, i, arr);
      }
    }
    
    Login or Signup to reply.
  3. You don’t need an inner loop:

    const arr = [1, 3, 5, 9, 11, 12]
    
    for (let i = 1; i < arr.length; ++i) {
      console.log(`${arr[i - 1]} and ${arr[i]}`);
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search