-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiffTwoArrays.js
More file actions
31 lines (26 loc) · 820 Bytes
/
Copy pathdiffTwoArrays.js
File metadata and controls
31 lines (26 loc) · 820 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function diffArray(arr1, arr2) {
const newArr = [];
let longerArr, shorterArr;
//Compare the length of the arrays and set them as new variables
if(arr1.length >= arr2.length) {
longerArr = arr1;
shorterArr = arr2;
} else {
longerArr = arr2;
shorterArr = arr1
}
//Use indexOf to test the longerArr against the shorterArr pushing differences to newArr
for(let i = 0; i < longerArr.length; i++) {
if(shorterArr.indexOf(longerArr[i]) === -1) {
newArr.push(longerArr[i]);
}
}
//Use indexOf to test the shorterArr against the longerArr pushing differences to newArr
for(let i = 0; i < shorterArr.length; i++) {
if(longerArr.indexOf(shorterArr[i]) === -1) {
newArr.push(shorterArr[i]);
}
}
return newArr;
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);