Last active
December 24, 2019 19:59
-
-
Save neharkarvishal/470beccc1c5eeae15c130361cc275f33 to your computer and use it in GitHub Desktop.
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
/** | |
* 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] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 truthyvalues and
Array.prototype.reduce()
to remove elements usingArray.prototype.splice()
. Thefn
is invoked with threearguments (
value
,index
,array
).