Nice approach. You first removed duplicate letters then checked each letter from the second array if it matches a letter from the first. A match increments the counter, then the function returns whether the counter is the same as the second array’s length.
Now let’s examine the code more closely Let’s start with deleteCopies()
.
tmpArr
is an array that contains unique values from the arr
argument. So you scan each element, then if that element is not yet in tmpArr
, that element is push
ed to tmpArr
.
Luckily there’s a built-in function in JS that checkes whether some value is already present in an array: Array.prototype.includes()
. Using this we can replace the big chunk of code in the for-loop with more concise and descriptive code:
function deleteCopies(arr) {
var tmpArr = [];
// For each item in `arr`, if that item is not included in `tmpArr`,
// push that item to `tmpArr`.
for (var i = 0; i < arr.length; i++) {
if (!tmpArr.includes(arr[i])) {
tmpArr.push(arr[i]);
}
}
// Now we have only an `if` in the for-loop and removed a bunch of variables.
return tmpArr;
}
Now let’s move to the mutation()
function. Here we note that we’re basically doing the same thing we did in deleteCopies()
: see if a letter from the second array is found in the first or not. Again we can use includes()
to do the job.
function mutation(arr) {
// ...
// code at the beginning omitted for this snippet...
// ...
// For each item in `str2Arr`, if that item is not included in
// `str1Arr`, immediately return `false`.
for(var i = 0; i < str2Arr.length; i++){
if (!str1Arr.includes(str2Arr[i])) {
return false;
}
}
// After looking through all items in `str2Arr`, we found that
// all of its items are included in `str1Arr`, so we return `true`
// after the loop.
return true;
}
Above, if we found that a letter in str2Arr
is not included in str1Arr
, we immediately return false
. This effectively stops the for-loop, but who cares? A letter in str2Arr
is not found in str1Arr
; there’s no more reason to loop through. That’s enough for us to return false
right on the spot.
Now, after looping through str2Arr
and we find that all of it’s letters are included in str1Arr
, we can return true
right after the for-loop.
Whew that’s a long post ! I’d like to say “Here’s a potato,” but this is not 9gag . Overall your’s is a good working solution. Good job ! But remember to come back to your solutions every now and then and improve them with newer things that you learned.
Cheers!