// 需求:一串字符串,例如:`1,2,3,4,5,6,6,7,8,8,9,8,6,6,5,5,4,4,4,4,3,3,1`
// 按出现次数排序
function sortByCount(str) {
// 1、字符串转数组
let strToArr = str.split(`,`);
// 2、定义两个空的数组
let arr1 = [];
let arr2 = [];
// 3、循环遍历
strToArr.forEach(val => {// indexOf() 找到数组的第一个索引,找不到就是 -1
let flag = arr1.indexOf(val);
console.log(flag);
if (flag < 0) {arr1.push(val);
arr2.push(1);
} else {arr2[flag]++;
}
});
let arrTmp = arr1.slice();
arr1.sort((a, b) => {let flaga = arrTmp.indexOf(a);
let flagb = arrTmp.indexOf(b);
return arr2[flagb] - arr2[flaga];
});
return arr1.toString();}
const res = sortByCount(`1,1,2,2,3,3,3,4`);
// 打印输出结果
console.log(res);