I have been doing this course for hours on free code camp, however, I found a solution that I do not understand and I am trying to put comments on each line to record as I achieve and understand it for future references and I already understand some lines but I cannot understand some parts of this code:
function destroyer(arr) {
// let's make the arguments part of the array
var args = Array.prototype.slice.call(arguments); // this would result into [[1, 2, 3, 1, 2, 3], 2, 3]
args.splice(0,1); // now we remove the first argument index on the array so we have 2,3 in this example
// I DO NOT UNDERSTAND THESE CODES BELOW
return arr.filter(function(element) {
return args.indexOf(element) === -1;
});
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
I already check on documentation and I find it hard to understand seems the code in this sample are very different. I would really appreciate your help!
arr in the section of code you don't understand refers to the first argument passed to the destroyer function; in this case, the array [1, 2, 3, 1, 2, 3]
arr.filter is using the Array.filter method to create a "filtered" version of the array with only those values that pass the "test" defined by function(element) { return args.indexOf(element) === -1; }
That function uses Array.indexOf to check if the sliced args array (which you correctly identified as being equal to [2, 3]) contains the given element. Because indexOf returns -1 when the element is not found, checking for that value is equivalent to checking that the specified element is NOT in the array
The result of all of this - and the return value of the function destroy - will be the array [1, 1], representing a filtered version of the array passed to destroy that contains all the values not equal to the other values passed to destroy.
Array.slice is part of the arrays prototype;
prototype methods are only accessable on instances of Classes.
var arr = ['a', 'b', 'c', 'd'];
// [] is JavaScript shorthand for instantiating an Array object.
// this means that you can call:
arr.slice(someArg1);
arry.splice(someArg2);
Related
The javascript includes function can be used to find if an element is present in an array. Take the following example:
var arr = ['hello', 2, 4, [1, 2]];
console.log( arr.includes('hello') );
console.log( arr.includes(2) );
console.log( arr.includes(3) );
console.log( arr.includes([1, 2]) );
Passing 'hello' or 2 to the function returns true, as both are present in the array arr.
Passing 3 to the function returns false because it is not present in the array.
However, why does arr.includes([1, 2]) return false as well, even though this is equal to the last element in the array? And if this method does not work, how else can I find whether my array includes the item [1, 2]?
.includes() method uses sameValueZero equality algorithm to determine whether an element is present in an array or not.
When the two values being compared are not numbers, sameValueZero algorithm uses SameValueNonNumber algorithm. This algorithm consists of 8 steps and the last step is relevant to your code , i.e. when comparison is made between two objects. This step is:
Return true if x and y are the same Object value. Otherwise, return false.
So in case of objects, SameValueZero algorithm returns true only if the two objects are same.
In your code, since the array [1, 2] inside arr array is identically different to [1, 2] that you passed to .includes() method, .includes() method can't find the array inside arr and as a result returns false.
The Array#includes checks by shallow comparison, so in your case the string and numbers are primitives there is only ever a single instance of them so you get true from Array#includes.
But when you check for array, you are passing a new array instance which is not the same instance in the array you are checking so shallow comparison fails.
To check for an array is included in another array first check if it is an array then do a deep comparison between the arrays.
Note that below snippet only works for an array of primitives:
var arr = ['hello', 2, 4, [1, 2]];
const includesArray = (data, arr) => {
return data.some(e => Array.isArray(e) && e.every((o, i) => Object.is(arr[i], o)));
}
console.log(includesArray(arr, [1, 2]));
But if you keep the reference to the array [1, 2] and search with the reference the Array#includes works as in this case the shallow comparison works perfectly (obeying same value zero algorithm):
const child = [1, 2];
const arr = ['hello', 2, 4, child];
console.log(arr.includes(child));
If you don't mind using lodash, this algorithm is accurate - unlike the accepted answer.
import _ from 'lodash';
export const includesArray = (haystack, needle) => {
for (let arr of haystack)
if (_.isEqual(arr, needle)) {
return true
}
return false
}
I am trying to compare two given parameters of a function. The exact problem is as follows:
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.
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); // expected output: [1,1]
I am using filter method to iterate over the array but I couldn't compare the args with the elements of the array inside the callback of the filter.
function destroyer(arr, ...args) {
let result = arr.filter(num => {
for (let i = 0; i<=args.length; i++ ){
num !== args[i]
}
});
return result;
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
I can iterate with for loop but I cannot use the output of for loop to do filter iteration.
Any ideas?
Probably an easier way to achieve the goal using .filter() with .includes(). Additionally you can use ...rest so called rest parameters for you function, see form the documentation:
The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
Try as the following:
const destroyer = (arr, ...rest) => {
return arr.filter(num => !rest.includes(num));
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
I hope this helps!
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Example:
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
via MDN
Filter iterates over all elements of some array and returns a new array. It puts an element in the new array only if callback (your function invoked as a parameter of filter) return true otherwise it's omitted.
Next it's worth to use rest parameters to achieve two arrays (initial and values to exclude).
The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
function sum(...theArgs) {
return theArgs.reduce((previous, current) => {
return previous + current;
});
}
console.log(sum(1, 2, 3));
// expected output: 6
console.log(sum(1, 2, 3, 4));
// expected output: 10
Solution with explanation:
//Declare your function, first parameter is initial array, the second one is also array created by using rest parameters
function destroyer(initialArray = [], ...toExclude) {
// filter initialArray, if el (single element) is NOT included in "toExclude" it returns true
// and add this particular element to the result array
let result = initialArray.filter(el => toExclude.includes(el) == false);
//return result
return result;
}
I am being given the function call destroyer([1, 2, 3, 1, 2, 3], 2, 3);. I want to be able to pull from the last 2, 3 part after the initial object, but I do not know how to go about this.
return arr[6]; and return arr[1][0] both return nothing. I am expecting to see 2 or 2, 3 (Last two numbers)
I tried researching Property Accessors, but I think I was looking in the wrong place for my answer.
Here's my full code:
function destroyer(arr) {
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
Instead of getting the first array [1,2,3,1,2,3]
I want to get the parts after the array:
[1,2,3,1,2,3],2,3
You're destroyer function is only taking one argument, but you're passing it 3.
You have two options:
Use arguments to get an array-like of all the passed arguments, you'll then need to combine that with a method like slice to get only the second and third arguments. Additionaly since arguments isn't technically an array, you need to convert it to one before you can call a method like slice. My example uses Array.from however that is only available on newer browsers.
function destroyer(arr) {
return Array.from(arguments).slice(1,3);
}
console.log('Result: ', destroyer([1, 2, 3, 1, 2, 3],2,3));
Add additional parameters to your function definition. This is probably easier if you know you'll have exactly 3 arguments. And there are far fewer gotchas compared to using the magic arguments variable.
function destroyer(a, b, c) {
return [b, c];
}
console.log('Result: ', destroyer([1, 2, 3, 1, 2, 3], 2, 3));
try use arguments
example
function destroyer(){var arr = []; arr.push(arguments[1]);arr.push(arguments[2]); return arr};
I am trying to figure out what the code below means. I got it from freecodecamp.com and I am doing one of the challenges on there. The challenge is called "Seek and Destroy". I am just one of those people that has to understand what is going on in order for me to proceed, so can someone please explain to me how this code works and what is does from top to bottom?
function destroyer(arr) {
var args = Array.prototype.slice.call(arguments);
return arr.filter(function(element){
return args.indexOf(element) === -1;
});
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
For example, what is the "element" parameter in the function for .filter() method? How does javascript know what "element" is in the first place? I have been asking people and reading descriptions of solutions, but every solution I read is very vague and is still confusing to me.
Side note: I already know the algorithm removes values from arr, but I just want to know how it does it.
var args = Array.prototype.slice.call(arguments);
This line takes all the arguments given in the function and places them into an array. In this case the value is [[1, 2, 3, 1, 2, 3], 2, 3].
return arr.filter(function(element){
...
});
The .filter() function takes an anonymous function which can have three parameters: element, index, and array. In this case the function iterates through the array arr being [1, 2, 3, 1, 2, 3]. For this function if true is returned the element is kept, if false is return the element is removed from the array.
return args.indexOf(element) === -1
Here we check if the array args has the element element. The .indexOf() method returns the index that the element is found, if it's not found -1 is returned. What this means is if the element is not found it returns true, otherwise it will return false (removing it from the array) if it was found.
Basically the above statements means for each element in the array [1, 2, 3, 1, 2, 3] if it's found in [2, 3] then it's removed. It technically checks [[1, 2, 3, 1, 2, 3], 2, 3], but the first check is against an array compared to an element which will always be false so it might as well be omitted.
Below are some brief comments stating what I mentioned above.
function destroyer(arr) {
// An array of the arguments
var args = Array.prototype.slice.call(arguments);
// For every element in the array arr remove elements found in args
return arr.filter(function(element){
return args.indexOf(element) === -1;
});
}
Can anyone explain to me how this code works? I looked for reduce and concat functions in Array, I understand these functions but I don't understand how this code works initialy:
var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(arrays.reduce(function(flat, current) {
return flat.concat(current);
}, []));
// → [1, 2, 3, 4, 5, 6]
Well actually it's a wrong use of .reduce(). For this job you don't need no initial array. Just the previous (p) and current (c) hand to hand can do it. Such as;
var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(arrays.reduce((p,c) => p.concat(c)));
Note: Initial is handy when the type of the returned value is different from the array items. However in this case you are processing arrays and returning an array which renders the use of initial redundant.
I've described each step for you.
var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(arrays.reduce(function(flat, current) {
// first loop: flat - [1,2,3], current - [4,5]
// [1,2,3].concat([4,5]) -> [1,2,3,4,5]
//second/last loop: flat - [1,2,3,4,5], current - [6]
// [1,2,3,4,5].concat([6]) -> [1,2,3,4,5,6]
//function stop
return flat.concat(current);
}, []));
You could add a console.log inside the callback we pass to the reduce and think about the output:
var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(arrays.reduce(function(flat, current) {
console.log('flat: '+ flat + 'current: ' + current)
return flat.concat(current);
}, []));
Initially we concat an empty array and the array [1,2,3]. So the result is a new array with elements [1,2,3]. Then we concat this array with the next element of the arrays, the array [4,5]. So the result would be a new array with elements [1,2,3,4,5]. Last we concat this array with the last element of the arrays, the array [6]. Hence the result is the array [1,2,3,4,5,6].
Ir order to understand in details the above you have to read about Array.prototype.reduce().
As it is stated in the above link:
The reduce() method applies a function against an accumulator and each
value of the array (from left-to-right) to reduce it to a single value
Furthermore the syntax is
arr.reduce(callback, [initialValue])
In you case the initialValue is an empty array, [].
So assuming we have the 2D array that you do: [[1, 2, 3], [4, 5], [6]] that is being reduced, the function is split into 2 main components.
array.reduce((accumulator, iterator) => {...}, initialValue);
flat - this is the accumulator of the reduction. It is given the initial value as passed into the second parameter of the reduce function and is used to store the values as the iterator passes through them.
current - this is the iterator that goes through all values within the data set being reduced.
So as you're iterating through the data set, your example is concatenating the accumulation array with the current value, and by the end you have your new array.
Array.reduce expects a callback with following signature:
function(previousElement, currentElement, index, array)
and an optional initial value.
In first iteration, if initialValue is passed, then previousElement will hold this value and currentElement will hold `firstArrayElement.
If not, then previousElement will hold firstArrayElement and currentElement will hold secondArrayElement.
For the following iterations, previousElement will hold value returned by previous iteration and currentElement will hold next value.
So in you example, initially flat holds [].
return flat.concat(current); will return a new merged array. This value will be used as flat for next iteration, and this process is returned. Finally, value returned by last iteration is used as final return value and is printed in console.