js judges the number of occurrences of an element

There are three important points:

1. Through nested for loops, compare each item of the array with all items in the entire array;

2. Through if judgment, if there is an equal item, count++, and set the equal item to -1, so that it can be judged that the item equal to -1 is a duplicate, and no new array is added;

3. Use if to judge !=-1, decide whether to add to the new array, and return.

function arrCheck(arr){
    
    
  var newArr = [];
  for(var i=0;i<arr.length;i++){
    
    
    var temp=arr[i];
    var count=0;
    for(var j=0;j<arr.length;j++){
    
    
      if(arr[j]==temp){
    
    
        count++;
        arr[j]=-1;
      }
    }
    if(temp != -1){
    
    
      newArr.push(temp+":"+count)
    }
  }
  return newArr;
}

arrCheck([1,2,3,3,4]); 
console.log(arrCheck([1,2,3,3,4]));

We can use reduce to solve this problem.
We initialize the type and value of the first parameter of the callback function in the second parameter of reduce, and convert the string to an array, then the result of the iteration will be an object, and each key value of the object is the letter of the string . Run it and feel it.

var arrString = 'abcdaabc';
sum =  arrString.split('').reduce(function(res, cur) {
    
     res[cur] ? res[cur] ++ : res[cur] = 1 return res; }, {
    
    })
console.log(sum)

Scan the code to get 1000+ front-end interview questions collection to try later

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/109048716