我们需要编写一个JavaScript函数,该函数接受一组文字值。然后,函数应计算输入数组每个元素的频率,并在此基础上准备一个新数组。
例如-如果输入数组是-
const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
那么输出应该是-
const output = [ [5, 3], [2, 5], [9, 1], [4, 1] ];
为此的代码将是-
const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const frequencyArray = (arr = []) => {
   const res = [];
   arr.forEach(el => {
      if (!this[el]) {
         this[el] = [el, 0];
         res.push(this[el])
      };
      this[el][1] ++
   }, {});
   return res;
};
console.log(frequencyArray(arr));输出结果
控制台中的输出将是-
[ [ 5, 3 ], [ 2, 5 ], [ 9, 1 ], [ 4, 1 ] ]