Thank you a lot. I think I am able to get it now thanks to your explanation in my second cleaner code.
The key for me was to use Array.from(arguments) which returns all the arguments into an array. By using console.log, the console showed the difference between function (arr) vs function (…arguments). With just using (arr), it only returns one argument whatever one it’s passed on, while (…arguments) will return all subsequent arguments after the first one. For example:
var countries = ["USA", "Panama", "Costa Rica", "Brazil", "Chile", "Guyana", "Canada", "Mexico", "Argentina", "Venezuela"];
function destroyer(arr){
console.log(arr);
}
destroyer(countries, "Ecuador", "Bolivia");//It will return only the full array of countries but the other arguments.
On the other hand:
function destroyer(arr){
console.log(Array.from(arguments));
}
destroyer(countries, "Ecuador", "Bolivia");//Will return an array of length of 3 elements
//Being index[0] the full countries array
//index[1] "Ecuador" and index[2] "Bolivia",
//plus any other subsequent arguments we want to add later
This is where my whole confusion was!!!
So after defining or converting the arguments object into a functional array with from() method, I would be able to select all tests arguments that start at index 1, so for this I select by using the splice method and defining a variable to it.
var testElements=Array.from(arguments).splice(1)
This way if we console.log into the function will return all array elements starting at index 1.
function destroyer(arr){
var testElements=Array.from(arguments).splice(1);
console.log(testElements);
}
destroyer(countries, "Ecuador", "Bolivia"); //will return Ecuador, Bolivia, etc
Having dominated this concept I could move on to the next step with it’s to iterate through the whole array using the filter method.
function destroyer(arr){
var testElements=Array.from(arguments).splice(1);
var newCountries=arr.filter(function(value){
});
}
Like any other loop or iteration we want us to return something. In this case we want to return all those array elements that aren’t present with the ones we test by using the indexOf
function destroyer(arr){
var testElements=Array.from(arguments).splice(1);
var newCountries=arr.filter(function(value){
return testElements.indexOf(value) === -1; //here it will return those elements that don't match the value parameter
//A -1 means they were no match elements
});
//Finally return the newCountries array
return newCountries;
}
destroyer(countries, "Brazil", "Canada", "Mexico");//It will return ["USA", "Panama", "Costa Rica", "Chile", "Guyana", "Argentina", "Venezuela"] and so on
This was very frustrating for me to understand, especially how arguments objects work and it really helped that I use console.log as debugging, something I’m not used to do.
Thank you a lot for your patience and reading all the way through my conclusions. Do you have any final comments to add? Do you know of any other challenges that uses argument objects?