So I wrote:
function diffArray(arr1, arr2) {
var newArr = [];
newArr = arr1.concat(arr2);
newArr.filter(num => !(arr1.includes(num) && arr2.includes(num)));
//console.log(newArr);
return newArr;
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
Yes, you pretty much are on the right track. The only problem is that .filter
does not change newArr
. It returns a new array which you can assign to something like
const resultArr = newArr.filter(...)
Yes I know thats what I was doing. Check to see if num is not in both original arrays and if so add it to newArr.
Your filter()
currently is doing nothing.
The newArr
is not changed by calling filter()
on it, and the result from calling filter()
is never saved into anything.
You can see it for yourself by uncommenting the console.log()
statement.
function diffArray(arr1, arr2) {
var newArr = [];
newArr = arr1.concat(arr2);
newArr.filter(num => !(arr1.includes(num) && arr2.includes(num)));
console.log(newArr.filter(num => !(arr1.includes(num) && arr2.includes(num))));
console.log(newArr);
return newArr;
}
Isn’t this saying if the newArr
contains a number that arr1 has then start with an empty array and push it to this newArr
?
newArr.filter(num => arr1.includes(num));
Right… But the filter
method does not modify newArr
, it creates a brand new array that contains the values from newArr
that return a truth value from the callback function.
So all on the same line like this?
let newArr = nums1.concat(nums2).filter(num => nums1.includes(num));
1 Like
I think that might work. You’d need to check the order of operations. Or you can return the result of the filter directly.
I’m not sure if the modified version of the filter callback you have does the same thing as your original filter callback.
system
Closed
February 10, 2022, 12:23pm
10
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.