Finding all points on the line where distance between each of them is dividable by X
I would think that on each iteration you could remove the elements that you include in Z, i.e. your first iteration will return [-3, 0] so you could remove them from A, they will never match anything else. My solution would be:



let input      = [-3, -2, 1, 0, 8, 7, 1];
let result     = [];
let workingSet = input;

while (workingSet.length) {
  let first    = workingSet[0];
  let elements = [];
  let unused   = [];
  
  workingSet.forEach( value =&gt; {
    if ((value - first) % 3 == 0) {
      elements.push(value);
    } else {
      unused.push(value);
    }  
  });
  
  console.log('elements', elements);
  if (elements.length &gt; result.length)
    result = elements;
  workingSet = unused;
}  
   
console.log('result', result);




One note is that you mix old style JS code like var with ES6 features like =&gt;. I would expect code to either stick to using the older JS style for maximum browser compatibility or to stick to the newer JS style consistently.