根据 JavaScript 中元素频率的增加对数组进行排序
问题
我们需要编写一个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]
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短