1. Write a method to remove the repeating elements of an array:
Method one: normal for loop nesting;
1 functionRemovesame (arr) {2 Console.log (arr);3 for(vari=0, len = arr.length; i<len; i++){4 for(varj=i+1; j<len-i; J + +){5 if(Arr[i] = = =Arr[j]) {6Arr.splice (Arr[j], 1);//Delete If duplicate elements are detected7j--;//move forward one index to prevent missing certain elements when there are multiple repeating elements8 }9 }Ten } One Console.log (arr); A returnarr; - } - the vararr = [1,2,3,3,3,3,3,4,4]; -Removesame (arr);
Method Two: Using for...in to remove weight;
1 functionRemovesame (arr) {2 varobj = {};3 varNEWARR = [];4 varkey;5 6 for(vari=0; i<arr.length; i++){7Key =Arr[i];8 if(Obj[key]) {9Obj[key] = 0;//if the object is not added, it is assigned a value of 0;Ten}Else{ OneObj[key] = 0;//if the object is added (that is, duplicate elements appear), it is overwritten with the original property, guaranteeing only one property name in the array; A }; - }; - the for(Keyinchobj) { -Newarr.push (key);//adds attributes from the removed object to the new array - }; - + Console.log (NEWARR); -}
Method Three: Use IndexOf () (IndexOf can return the index position of the element in the array);
1 functionOnlyone (arr) {2 varArr1=[];//array to hold the removed heavy elements3 for(vari=0;i<arr.length;i++){4 if(Arr1.indexof (Arr[i]) ==-1) {//whether the first element of ARR has been saved in arr1, if saved, skipped (that is, duplicate elements are not in the array); Push the current item into the array5 Arr1.push (Arr[i]);6 }7 }8 returnarr1;9}
2. Determine the most frequently occurring characters in a string, and count the number of times:
1 functionGetmaxletter () {2 varobj={};//Save the characters and occurrences of the split3 4 for(varI=0, L=str.length, K; i<l; i++){5K = Str.charat (i);//extracts the characters from a string6 if(Obj[k]) {7obj[k]++;//The index of the character as the value of the object, or + + if it has occurred8}Else{9Obj[k] = 1;//If none of the elements in the object is assigned a value of 1, indicating that 1 occurrencesTen } One } A console.log (obj); - - varm = 0;//Maximum number of occurrences the varMyarr = [];//the maximum number of characters that are used to hold the same amount in a string - - for(varKinchobj) {//for in iterates over the property values in the object (that is, the individual characters) - if(Obj[k] >= m) {//if there is greater than the maximum value, the value is re-assigned + if(Obj[k] >m) { -Myarr = []; + } AMyarr.push (k);//if equal, the same character is stored in the array atm = Obj[k];//number of fetches - } - } -Console.log (' Most occurrences of the characters are: ' + Myarr + ', occurrences: ' +m); - } - in varstr = "Hello worlllllddddddd"; -Getmaxletter (str);
Several small programming questions (array de-weight, get the most characters in the string)