Reputation: 1162
I have a quick question about finding the difference between two arrays. I found a chunk of JavaScript code that does what I want here and modified it a bit:
JS
function diffArray(arr1, arr2) {
var newArr = [];
var myArr = arr1.concat(arr2);
newArr = myArr.filter(function(item){
return arr2.indexOf(item) < 0 || arr1.indexOf(item) < 0;
});
return newArr;
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
However, I'm not sure that I really understand what the filter function is doing here. Could anyone give me a clear explanation of how this works.
Note: I already know the basics of filter functions. I'm looking for a specfic explanation of this filter.
Upvotes: 1
Views: 107
Reputation: 2672
Easy way of thinking this is that filter function is internally creating an array. The elements of this internal array are the ones that pass the condition in the callback function. This is possible since this decision is being made one element at a time in the callback function.
Condition arr2.indexOf(item) < 0 || arr1.indexOf(item) < 0 passes only for element 4 since at that time 4 is not present inside arr1. Since true is returned element 4 is added in the internal array. Ultimately 4 is returned in newArr.
Upvotes: 0
Reputation: 1149
Filter is using a lambda to filter the list.
This essentially means that it executes the code between the { } and returns an array that meets the criteria. Your criteria are that the index of the item is greater than 0 in both arrays which is essentially just saying it's in both arrays.
you can read more here: https://www.w3schools.com/jsref/jsref_filter.asp
Upvotes: 0
Reputation: 41893
newArr = myArr.filter(function(item){
return arr2.indexOf(item) < 0 || arr1.indexOf(item) < 0;
});
The Array#filter
function iterates over each element of the newly made array from concat
function (containing every element from arr1
and arr2
arrays).
If at least one of the conditions arr2.indexOf(item) < 0
or arr1.indexOf(item) < 0
is fulfilled (returns true
) at some iteration, the Array#filter
function filters out (returns) that specified (actually iterated) element.
In case, if the iterated element is both in arr1
and arr2
, the indexOf
function will return it's index (which is higher than 0
) - the condition will return false
(it's not smaller than 0
). We will receive then false || false
which is false
and that element won't be included in the newArr
array, containing unique elements.
In case, if given element is only in one array (it doesn't exist in the second one - it's index will return -1
- it will fulfill the < 0
condition) - one of the conditions will return true
, so the both conditions will become true || false
which is true
- given element will be included in the newArr
array.
Upvotes: 4