A
A
Arkady Tagirov2017-02-22 19:58:35
JavaScript
Arkady Tagirov, 2017-02-22 19:58:35

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]

I don't understand how it returns an element that is not in arr2 but is present in arr1. Thanks for the answer. return b.indexOf(value) === -1;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
holymotion, 2017-02-22
@Dude1321

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.

N
nirvimel, 2017-02-22
@nirvimel

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]

Here is an example of solving the same problem for 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 question

Ask a Question

731 491 924 answers to any question