Rotation snapping, find next closest quaternion from an array

I am rotating a cube around a particular axis (x or y or z) by dragging my mouse, lets say while dragging I calculate how much angle rotation I have to appy.
Now I have my current cube rotation in quaternion, and also an array of quaternions containing quaternions of 0, 45, 90, 135, 180, 225, 270, 315, and 360 degrees.
When I am rotating my cube I want to find the closest quaternion from the array, lets say I am rotating in anti-clock and my cube is at 30, then the closest will be quaternion of 90 degrees from the array., similarly for 170 I should get 180 deg quaternion from the array.
currently I am maintaining a variable and depending upon the direction (clock or anti-clock) I am rotating the cube I am managing that variable and finding the next required quaternion from the array. But I need a more efficient way if it exists.

currently My code is doing something like this, If anyone have some solution about this, or a new way of doing this, then please help me


function handleDrag() { 
  let target = new THREE.Vector3();
  raycaster.setFromCamera(mouseNDC, camera);
  raycaster.ray.intersectPlane(Zplane, target);

  let temp = target
  
  target.sub(mesh.position);   // final vector after drag
  initial.sub(mesh.position);    // initial vector

  // get rotation direction using cross product
  let xx = new THREE.Vector3().copy(target).normalize()
  let yy = new THREE.Vector3().copy(prevDir).normalize()
  let dir = yy.cross(xx).z

  const angleBtwVec = angleInPlane(initial, target, Zplane.normal);
  let quaternion = new THREE.Quaternion();
  quaternion.setFromAxisAngle(new THREE.Vector3(0, 1, 0), angleBtwVec);

  let effectiveQuatChange = new THREE.Quaternion().copy(initialCubeQuat)
  effectiveQuatChange.multiply(quaternion)

  // find next quaterion for which we need to compare for snapping 
  let check = next
  if (dir > 0) {   // then anti-clock
    check = (next + 1) % 8
  } else {     // else rotation is in clock direction
    check = (next - 1 + 8) % 8
  }

  // apply quaternion change
  mesh.quaternion.copy(effectiveQuatChange)

  let reqQuatArray = quaternionArrayYR
  let angleDiff = toDegrees(mesh.quaternion.angleTo(reqQuatArray[check]))
  
  console.log(angleDiff, check);

  if (angleDiff <= 15) {   // if mesh angle with next req quaternion is less than 15 degree, then set mesh quaternion to required quaternion
    next = check
    mesh.quaternion.copy(reqQuatArray[next]);
    initialCubeQuat.copy(reqQuatArray[next]);
    initial = temp;
  }

  prevDir = temp
}