JavaScript中的数组元素[duplicate]

k97glaaz  于 2023-01-24  发布在  Java
关注(0)|答案(1)|浏览(158)
    • 此问题在此处已有答案**:

(41个答案)
(39个答案)
16小时前关门了。

  • 我在努力做什么:给定一个数字数组,例如:["1", "2", "1", "1", "2", "2", "3"],我想找到数组中**重复次数最多的元素。但是,我还想知道是否有多个元素满足要求,以及这些元素是什么。
  • 我还想不出该怎么开始...
blmhpbnm

blmhpbnm1#

这是一种使用Array.reduce()的方法
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

  • 首先,通过返回{"1": 3, "2": 3, "3": 1}这样的对象,确定数组中每个唯一值出现的次数
  • 然后,通过返回类似{"count": 3, "values": ["1", "2"]}的对象,确定数组中出现次数最多的值
const data = ["1", "2", "1", "1", "2", "2", "3"];

//returns the number of time each unique value occurs in the array
const counts = data.reduce( (counts, item) => {
  if(item in counts)
    counts[item] += 1;
  else
    counts[item] = 1;
  return counts;
}, {});

console.log(counts);
/*
{
  "1": 3,
  "2": 3,
  "3": 1
}
*/

//returns which values and how many times occur the most 
const max = Object.entries(counts)
  .reduce((max, [value, count])=> {
      if(count < max.count)
        return max;
      if(count == max.count){
        max.values.push(value);
        return max;
      }
      return {count: count, values: [value]};
    },{count: 0, values: []});

console.log(max);
/*
{
  "count": 3,
  "values": [
    "1",
    "2"
  ]
}
*/

相关问题