Skip to content

Instantly share code, notes, and snippets.

@lap00zza lap00zza/shiftArray.js
Last active Nov 10, 2018

Embed
What would you like to do?
Shift an array to left or right
// +by shift left
// -by shift right
const shiftArray = (arr, by) => {
const _by = (by | 0) % arr.length;
const rest = by > 0 ? arr.slice(0, _by) : arr.slice(_by);
return arr.map(
(_, i) => arr[i + _by] !== undefined
? arr[i + _by]
: rest.shift()
);
};
// Example:
// const arr = [1, 2, 3, 4]
// shiftArray(arr, 1) -> [2, 3, 4, 1]
// shiftArray(arr, 2) -> [3, 4, 1, 2]
// shiftArray(arr, -1) -> [4, 1, 2, 3]
// shiftArray(arr, -2) -> [3, 4, 1, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.