Skip to content

Instantly share code, notes, and snippets.

@speckworks
Last active June 17, 2020 13:19
Show Gist options
  • Save speckworks/69f207bb0180c9495bc40d587ba53665 to your computer and use it in GitHub Desktop.
Save speckworks/69f207bb0180c9495bc40d587ba53665 to your computer and use it in GitHub Desktop.
//This algorithm is O(n) because as it creates a new Array taking up
//(1/2 * n) amount of memory as n becomes arbitrarily large.
const onlyElementsAtEvenIndices = (array) => {
let newArray = Array(Math.ceil(array.length / 2 ));
for (let i = 0; i < array.length; i++) {
if (i % 2 === 0) {
newArray[i / 2] = array [i]
}
}
return newArray;
}
onlyElementsAtEvenIndices([2,3,4,5,6,7]);
//returns [2,4,6] <--- interesting aside, "0" is an "even number"?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment