Created
August 13, 2019 14:12
-
-
Save lancevo/ac2702b300b7613dc7c404f8ee9742b1 to your computer and use it in GitHub Desktop.
Filter array in place
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function filterInPlace(array, condition) { | |
let iOut = 0; | |
for (let i = 0; i < array.length; i++) { | |
if (condition(array[i])) { | |
array[iOut++] = array[i]; | |
} | |
} | |
array.length = iOut; | |
} | |
const arr = []; | |
for (let i = 0; i<100; i++) { | |
arr.push(i); | |
} | |
filterInPlace(arr, (n) => n % 2); // [0,2,4,6...] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this modifies the array in place to save memory, and performant