Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If the index is greater than arr length it should go back round again [duplicate]

function getAnyItem(arr, position) {
  if (position > arr.length) {
   return position = arr[0] ;
  }
  let index = arr[position];
  return index;

 }

I am really struggling on finding a way to go back round an array without using loops.Above is what I have written so far, all I get it undefined. Any help would be much appreciated as I am new to coding.

getItem(['a','b','c'], 10) should return 'b'

like image 658
edwrdcodeu Avatar asked Oct 27 '25 03:10

edwrdcodeu


1 Answers

You could take the remainder operator % with the length of the array

function getItem(arr, position) {
   return arr[position % arr.length];
}

console.log(getItem(['a','b','c'], 10)); // 'b'
like image 89
Nina Scholz Avatar answered Oct 29 '25 18:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!