Skip to content

Instantly share code, notes, and snippets.

@neharkarvishal
Last active December 24, 2019 19:59
Show Gist options
  • Save neharkarvishal/470beccc1c5eeae15c130361cc275f33 to your computer and use it in GitHub Desktop.
Save neharkarvishal/470beccc1c5eeae15c130361cc275f33 to your computer and use it in GitHub Desktop.
/**
* removeArrayElements.js
* tags: { JavaScript, Array }
* Removes elements from an array for which the given function returns false.
* Use Array.prototype.filter() to find array elements that return truthy
* values and Array.prototype.reduce() to remove elements using
* Array.prototype.splice(). The func is invoked with three
* arguments (value, index, array).
*/
const remove = (arr, fn) => {
return arr
.filter(fn)
.reduce( (acc, val) => {
arr.splice( arr.indexOf(val), 1 );
return acc.concat(val);
}, []
);
};
console.log(
remove([1, 2, 3, 4], n => n % 2 === 0) // [2, 4]
);
@neharkarvishal
Copy link
Author

removeArrayElements.js

tags: { JavaScript, Array }
Removes elements from an array for which the given function returns false.
Use Array.prototype.filter() to find array elements that return truthy
values and Array.prototype.reduce() to remove elements using
Array.prototype.splice(). The fn is invoked with three
arguments (value, index, array).

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