Skip to content

Instantly share code, notes, and snippets.

@bytrangle
Last active December 29, 2020 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bytrangle/cc622a807a76a32cfd3f62a608707b0c to your computer and use it in GitHub Desktop.
Save bytrangle/cc622a807a76a32cfd3f62a608707b0c to your computer and use it in GitHub Desktop.
Find nth element from a given index going leftward
/* Suppose we have an array [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].
Given number is 4 at index 3.
How to find the 5th number from the given number above going backwards?
Result should be 11. Note that once our loop reaches the beginning of the array, we will continue to loop from the end
going backwards.
*/
function findElem(arr, givenIndex, offset) {
const subtract = givenIndex - offset;
let cur;
if (subtract >= 0) {
cur = arr[subtract];
} else {
/* Given index less than offset means that we will need to continue to loop
through the array backward */
let count = Math.abs(subtract);
console.log(count);
for (var i = arr.length - 1; count > 0; i--) {
cur = arr[i]
count -= 1;
}
}
return cur;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var output = findElem(arr, 3, 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment