Skip to content

Instantly share code, notes, and snippets.

@martin-mok
Last active January 11, 2020 17:51
Show Gist options
  • Select an option

  • Save martin-mok/55be3777712d483dda05555275188184 to your computer and use it in GitHub Desktop.

Select an option

Save martin-mok/55be3777712d483dda05555275188184 to your computer and use it in GitHub Desktop.
freecodecamp: Seek and Destroy

Description

You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
Note: You have to use the arguments object.

Tests

tests:
  - text: <code>destroyer([1, 2, 3, 1, 2, 3], 2, 3)</code> should return <code>[1, 1]</code>.
    testString: assert.deepEqual(destroyer([1, 2, 3, 1, 2, 3], 2, 3), [1, 1]);
  - text: <code>destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3)</code> should return <code>[1, 5, 1]</code>.
    testString: assert.deepEqual(destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3), [1, 5, 1]);
  - text: <code>destroyer([3, 5, 1, 2, 2], 2, 3, 5)</code> should return <code>[1]</code>.
    testString: assert.deepEqual(destroyer([3, 5, 1, 2, 2], 2, 3, 5), [1]);
  - text: <code>destroyer([2, 3, 2, 3], 2, 3)</code> should return <code>[]</code>.
    testString: assert.deepEqual(destroyer([2, 3, 2, 3], 2, 3), []);
  - text: <code>destroyer(["tree", "hamburger", 53], "tree", 53)</code> should return <code>["hamburger"]</code>.
    testString: assert.deepEqual(destroyer(["tree", "hamburger", 53], "tree", 53), ["hamburger"]);
  - text: <code>destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan")</code> should return <code>[12,92,65]</code>.
    testString: assert.deepEqual(destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan"), [12,92,65]);

Solution

My Soln:

function destroyer(arr) {
  // Remove all the values
  let removeList=[...arguments].slice(1);
  return arr.filter(e=>removeList.indexOf(e)===-1);
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Offical soln:

function destroyer(arr) {
  var hash = Object.create(null);
  [].slice.call(arguments, 1).forEach(function(e) {
    hash[e] = true;
  });
  // Remove all the values
  return arr.filter(function(e) { return !(e in hash);});
}

Further readings

9 Ways to Remove Elements From A JavaScript Array - Plus How to Safely Clear JavaScript Arrays
Includes() vs indexOf() in JavaScript
in operator - MDN

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