1、javascript求数组中第k大元素出现的次数:
function getNum(arr,k){
arr.sort((a,b)=> b-a);
let uniqarr = Array.from(new Set(arr));
let index = arr.indexOf(uniqarr[k-1]);
let num;
if(k == arr.length){
num = arr.length - index
}else{
let indexnext = arr.indexOf(uniqarr[k])
num = indexnext - index;
}
return num
}
console.log(getNum([1,2,3,4,4,4,5,6],3)) //3
2、数组对象扁平化
function flatten(arr) {
let result=[]
for (let i=0,len=arr.length;i<len;i++) {
if (arr[i] instanceof Array) {
result=result.concat(flatten(arr[i]))
} else {
result.push(arr[i])
}
}
return result
}
console.log(flatten([1,2,[1,4],[3]])) //[1,2,1,4,3]
3、判断回文字符串(一个字符串从前往后读,和从后往前读是一样的)
function isPalindRome(input){
if(typeof input !== 'string') return false
let len = input.length;
let str = ''
for(let i=len-1; i>=0; i--){
str += input[i];
}
return str == input;
}
console.log(isPalindRome("ABCBA"))//true
4、判断字符串中出现最多的字符,以及出现次数
function getMax(input){
let arr = input.split("");
let obj = {}
arr.forEach((val,index) => {
//遍历数组,把数组元素存入对象,赋初始值为1,如果对象中已经存在该元素,则加一
if(obj[val]){
obj[val]+=1
}else{
obj[val] = 1;
}
});
let num = 0,
res;
for(let i in obj){
if(num<obj[i]){
num = obj[i];
res = i;
}
}
return (res+':'+num)
}
console.log(getMax("ABBCCCD")) //C:3
5、快排
function quickSort(arr){
if(arr.length <=1) return arr;
let pivotIndex = Math.floor(arr.length / 2);
let pivot = arr.splice(pivotIndex,1)[0];
let left = [];
let right = [];
for(let i = 0 ; i<arr.length;i++){
if(arr[i]<pivot){
left.push(arr[i]);
}else{
right.push(arr[i])
}
}
return quickSort(left).concat([pivot],quickSort(right));
}
console.log(quickSort([1,2,3,1,5,2,6,2,7,3]))
//[1, 1, 2, 2, 2, 3, 3, 5, 6, 7]