根据 JavaScript 中元素出现频率的增加对数组进行排序

javascriptweb developmentfront end technology

问题

我们需要编写一个 JavaScript 函数,该函数将数字数组 arr 作为第一个也是唯一的参数。

数组 arr 可能包含一些重复项。我们的函数应该以这样的方式对数组进行排序:出现次数最少的元素放在最前面,然后是出现频率增加的元素。

如果两个元素在数组中出现的次数相同,则应按递增顺序排列。

例如,如果函数的输入是

输入

const arr = [5, 4, 5, 4, 2, 1, 12];

输出

const output = [1, 2, 12, 4, 4, 5, 5];

输出说明

数字 1、2 和 12 都出现一次,因此按升序排序,然后 4 和 5 都出现两次。

示例

以下是代码 −

const arr = [5, 4, 5, 4, 2, 1, 12];
const sortByAppearance = (arr = []) => {
   arr.sort((a, b) => a - b);
   const res = [];
   const searched = {};
   const countAppearance = (list, target) => {
      searched[target] = true;
      let count = 0;
      let index = list.indexOf(target);
      while(index !== -1){
         count++;
         list.splice(index, 1);
         index = list.indexOf(target);
      };
      return count;
   };

   const map = [];
   arr.forEach(el => {
      if(!searched.hasOwnProperty(el)){
         map.push([el, countAppearance(arr.slice(), el)]);
      };
   });
   map.sort((a, b) => a[1] - b[1]);

   map.forEach(([num, freq]) => {
      while(freq){
         res.push(num);
         freq--;
      }
   });
   return res;
};
console.log(sortByAppearance(arr));

输出

[1, 2, 12, 4, 4, 5, 5]

相关文章