使用while循环查找JS数组中最常见的项目?

我创建了一个函数,该函数查找带有两个for循环的JS数组中最常见的项目,并显示该项目以及该数组中存在多少次。我该如何使用while循环?

var arr = [3,'a',2,3,4,9,3];

//ta = times appeared / m = max / arrchar = array character
var ta = 1;
var m = 0;
var arrchar;

for (var i = 0; i < arr.length; i++) {
  for (var j = i; j < arr.length; j++) {
    if (arr[i] == arr[j])
      m++;
    if (ta < m) {
      ta = m;
      arrchar = arr[i];
    }
  }
  m = 0;
}
console.log(arrchar + "(" + ta + ")");

GAOWEI324 回答:使用while循环查找JS数组中最常见的项目?

进行while循环的目的是使用退出条件。由于没有退出条件,因此我基本上创建了一个相当有效的for循环算法,只是将for循环替换为while循环。

var arr = [3,'a',2,3,4,9,3];

var occurences = {};

var max = 0;
var champion;

var index = 0;

while (index < arr.length) {
  var item = arr[index];
  occurences[item] = (occurences[item] || 0) + 1;
  if (occurences[item] > max) {
    max = occurences[item];
    champion = item;
  }
  index += 1;
}

console.log(`${champion} has ${max} occurences`);

不幸的是,上面的代码将始终将3"3"视为相同的值。如果您不希望发生这种情况,则应改用地图。

var arr = [3,3];

var occurences = new Map();

var max = 0;
var champion;

var index = 0;

while (index < arr.length) {
  var item = arr[index];
  var newSize = (occurences.get(item) || 0) + 1;
  occurences.set(item,newSize);
  if (newSize > max) {
    max = newSize;
    champion = item;
  }
  index += 1;
}

console.log(`${champion} has ${max} occurences`);

,

您可以使用数组精简器:

const arr = [3,3];

let max,winner;

const arrReduce = arr.reduce((acc,curr,index) => {
  acc[curr] = acc[curr] ? acc[curr] += 1 : 1;
  if(max < acc[curr]) winner = curr
  max = max > acc[curr] ? max : acc[curr];
  return acc;
},{});

console.log(max,winner)

,

您可以在while循环中使用过滤器方法。为每个arr索引创建一个过滤数组。如果过滤后的数组的长度大于maxOccurence,则将过滤后的数组的长度设置为maxOccurence。您可以尝试其他数组原型方法。可能有一种更简单的方法。

var arr = [3,3];

var char = "";
var maxOccurence = 0;
var i = 0;

while(i < arr.length){
  var filteredArr = arr.filter(x=> x === arr[i]);
  if(filteredArr.length > maxOccurence){
    char = arr[i];
    maxOccurence = filteredArr.length;
  }
  i++;
}
console.log(char + "(" + maxOccurence + ")");

,

运行以下代码。它将为您带来最期待的结果。

const arr = [3,'a','a','a',2,3,'a',3,'a',2,4,4,9,3];

// result array
var result = [];

$.each(arr,function( index,value ) {
    if(result[value] === undefined) 
        result[value] = 1;
    else
        result[value] = result[value] + 1;
});

console.log(result);
本文链接:https://www.f2er.com/3168005.html

大家都在问