Take out the elements of the common part of array 1 and array 2
Thought 1: Put the array 1 into the map, and then iterate over the array 2, the elements in arrays 2 do not exist in the map does not work, if the element in the array 2 already exists in the map, push it into a new array newarr, and finally return the new array.
function Getsamenums (ARR1,ARR2) { var mp={}; var newarr=[]; for (Var i=0;i<arr1.length;i++) { if (!mp[arr1[i]) { mp[arr1[i]]=1; } } for (Var i=0;i<arr2.length;i++) { if (Mp[arr2[i]) { newarr.push (arr2[i]);} } return NEWARR;} var arr1 = [4,2,1,10,5];var arr2 = [2,3,4,0,10,5];console.log (Getsamenums (ARR1,ARR2)];
Thought 2: Sort the array 1, array 2 in ascending order, and then iterate from the beginning, comparing. If equal, the element is push into a new array, and if the element in array 1 is larger than the element in array 2, the element in the array 1 is compared to the next element in array 2, and if the element in array 1 is less than that element in array 2, Compares the next element in the array 1 with the element in array 2
var arr = []; Arr1.sort (sortby); Arr2.sort (sortby); var i=0;
var j=0; while (I<arr1.length && J < arr2.length) { if (arr1[i] = = Arr2[j]) { arr.push (arr1[i]); i++;
j + +; } else if (Arr1[i]>arr2[j]) { j + +; } else{ i++; } } return arr;} var arr1 = [4,2,1,10,5];var arr2 = [2,3,4,0,10,5];console.log (Getsamenums (ARR1,ARR2)];
Thought 3: Sort the array 1 in ascending order, define a new global array, and then iterate over the array 2, using the binary lookup to determine whether the element in array 2 is in array 1, does not operate, then push it into a new array, and finally return. Call the method, and then print out the new array.
function SortBy (A, b) {return a-a ;} var newArr = [];
function BinarySearch (arr,findval,leftindex,rightindex) { if (leftindex>rightindex) { return; } var Midindex=math.floor ((Leftindex+rightindex)/2); var midval=arr[midindex]; if (midval>findval) { binarysearch (arr,findval,leftindex,midindex-1); } else if (midval<findval) { binarysearch (arr,findval,midindex+1,rightindex); } else{ Newarr.push (findval) return;} } function Getsamenums (ARR1,ARR2) { arr1.sort (sortby); for (Var i=0;i<arr2.length;i++) { binarysearch (arr1,arr2[i],0,arr1.length-1); }} var arr1 = [4,2,1,10,5];var arr2 = [2,3,4,0,10,5];getsamenums (ARR1,ARR2); Console.log (NEWARR);
JavaScript Little Exercise 3