Skip to content

Instantly share code, notes, and snippets.

@lancevo
Created August 13, 2019 14:12
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 lancevo/ac2702b300b7613dc7c404f8ee9742b1 to your computer and use it in GitHub Desktop.
Save lancevo/ac2702b300b7613dc7c404f8ee9742b1 to your computer and use it in GitHub Desktop.
Filter array in place
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...]
@lancevo
Copy link
Author

lancevo commented Aug 13, 2019

this modifies the array in place to save memory, and performant

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment