Answer the question
In order to leave comments, you need to log in
How does this function return the elements of one array that are missing from another?
Here is the code:
function diffArray(arr1, arr2) {
var diff = function(a, b) {
return a.filter(function(value) { return b.indexOf(value) === -1; });
};
return diff(arr1, arr2).concat(diff(arr2, arr1));
}
diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);
//Возвращает: ["piglet",4]
return b.indexOf(value) === -1;
Answer the question
In order to leave comments, you need to log in
You have a diffArray function, it is called with 2 arrays passed to it, this function (diffArray) returns the result of calling the nested diff functions (and the concatenation of their results)
In the nested function, we call the filter method, in the example above filter returns a new array of elements tested for occurrence of substrings. The indexOf method for Array, searches the specified array "b" for the specified value (value) of the array "a", in case of "not found" -1 is returned.
It turns out that we are going through all the elements of the array a looking for mismatches in the array b, the result of this passage is - new array.
How does it work? - TERRIBLE! Because, despite the beautiful appearance, its computational complexity is O (m * n)
! And this is unacceptable for a problem that has simple solutions with less computational complexity.
function diff(a, b) {
const b_set = new Set(b);
return a.filter(x => !b_set.has(x));
}
console.log(diff([1, 2, 3, 4], [5, 4, 3, 2])); // result === [1]
O (m + n)
(initially, I made a mistake with the complexity estimate, but in the comments, together with Interface , we came to the truth in this matter).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question