* fix: restructure certifications guide articles * fix: added 3 dashes line before prob expl * fix: added 3 dashes line before hints * fix: added 3 dashes line before solutions
4.3 KiB
title
| title |
|---|
| Seek and Destroy |
Seek and Destroy
Problem Explanation
This problem is a bit tricky because you have to familiarize yourself with Arguments, as you will have to work with two or more but on the script you only see two. Many people hardcode this program for three arguments. You will remove any number from the first argument that is the same as any other other arguments.
Relevant Links
Hints
Hint 1
You need to work with arguments as if it was a regular array. The best way is to convert it into one.
Hint 2
You need to filter, this also means you need to create a callback function. You can use various methods like: indexOf(), includes(). If you need another approach, reduce() might also be of use; keep reading those docs!
Hint 3
To convert arguments into an array use this code var args = Array.prototype.slice.call(arguments);
Solutions
Solution 1 (Click to Show/Hide)
function destroyer(arr) {
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < args.length; j++) {
if (arr[i] === args[j]) {
delete arr[i];
}
}
}
return arr.filter(Boolean);
}
Code Explanation
-
Create an array of
argumentsusingArray.prototype.slice.call()and store it in the variableargs. We'll use this to check againstarr. -
Start a basic
forloop to iterate througharr. Nest anotherforloop inside the first, changing the integer variablejand arr to args. This second loop will iterate throughargs.-
Within the second loop create an
ifstatement, checking strictly===that the current val ofarr[i]is equal toargs[j]. -
If the value at the current index is equal in both arrays, use
deleteto remove it fromarr.
-
-
Outside of the nested loops: return the modified array using the
Booleanobject as a filter for anynull's created by thedeleteoperator.
Relevant Links
- [arguments
- Array.filter()
- delete
- Boolean
Solution 2 (Click to Show/Hide)
function destroyer(arr) {
var args = Array.from(arguments).slice(1);
return arr.filter(function(val) {
return !args.includes(val);
});
}
Code Explanation
-
Declare a variable named
argsand set it equal to a newArrayobjectfrom()theargumentspassed into the function. On the same or next line, use theslice()method onargsstarting from the second index, 1. This separates the arguments used for filtering into their own array ofargs. -
Return the filtered array, using
includes()in the callback function to check ifvalis not inargs; returningtrueto keep the value in the original array orfalseto remove it.
Relevant Links
Solution 3 (Click to Show/Hide)
const destroyer = (arr, ...args) => arr.filter(i => !args.includes(i));
Code Explanation
- Code using ES6 syntax to declare function using arrow functions.
- Using spread operator to retrieve the arguments.
- Return the filtered array, using
includes().