Skip to content

Instantly share code, notes, and snippets.

@pbzona
Last active May 25, 2018 02:36
Show Gist options
  • Save pbzona/79c3099a3d4f5416f93009b1e1c42478 to your computer and use it in GitHub Desktop.
Save pbzona/79c3099a3d4f5416f93009b1e1c42478 to your computer and use it in GitHub Desktop.
why this thing works
// Set up the function, using the spread operator to structure arguments
var removeFromArray = function(...args) {
// Define the array as the first argument
const array = args[0]
// Returns a new array that does not contain any of [args]
return array.filter(val => !args.includes(val))
}
// So for the following array:
var someArray = [1, 2, 3, 4, 5]
// For example, when you call...
var result = removeFromArray(someArray, 3, 4);
// ...the function runs .filter(), which iterates over every item in the array it's called upon.
// In the example, .filter() is called on args[0] - the array - and on each iteration it checks
// to ensure [args] does not include the element at the current index.
// So when you run removeFromArray with the arguments in the example...
// ...you're filtering the array [1, 2, 3, 4, 5] for items contained in
// the set [[1, 2, 3, 4, 5], 3, 4].
console.log(result);
// [1, 2, 5]
// Since [1, 2, 5] are not members of the set [[1, 2, 3, 4, 5], 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment