写个(粗糙)方法:统计一下这个字符串中的哪个字符出现的次数最多:字符和次数

数组去重和取值##

function selectWhatYouWant (Istring) {
	var index = -1;
	var max = 0;
	var max_string = "";
	if(typeof Istring != "string"){
        return;
	}
	Array.prototype.unique_NSTS = function() {
		var res = [];
		var json = {};
		for (var i = 0; i < this.length; i++) {
			let count = 0;
			if (!json[this[i]]) {
				res.push(this[i]);
				json[this[i]] = 1;
			}
		}
		return res;
	}
	Istring = Istring.replace(/\s/g, "");
	_Istring = Istring.split("");
	_Istring = _Istring.unique_NSTS();
	
	for (var i = _Istring.length - 1; i >= 0; i--) {
		let count = 0;
		do {
			index = Istring.indexOf(_Istring[i], index + 1);
			if (index != -1) {
				count++
			}
		} while (index != -1);
		if (count > max) {
			max = count;
			max_string = _Istring[i];
		}
	}
	return console.log(max_string + "次数为" + max);
}

var textk = 'Ajax Login and Ajax Logout in Koa2, based on koa-passport and passport-local';
selectWhatYouWant(textk);

    //es6很强大
    var textk = 'Ajax Login and Ajax Logout in Koa2, based on koa-passport and passport-local';
textk = Object.entries(textk.replace(/\s+|[^\w]/g, '').split('').reduce((acc, cur) => {
	if (cur in acc) {
		acc[cur]++
	} else {
		acc[cur] = 1
	}
	return acc
}, {})).reduce(function(acc, cur) {
	//   console.log(acc)
	if (acc[1] > cur[1]) {
		return acc
	} else {
		return cur
	}
});
console.log(textk)

ES6中新增了Set数据结构,类似于数组,但是 它的成员都是唯一的 ,其构造函数可以接受一个数组作为参数,如:

     let array = [1, 1, 1, 1, 2, 3, 4, 4, 5, 3];
     let set = new Set(array);
     console.log(set);
     // => Set {1, 2, 3, 4, 5}

数组对象去重

var arr = [{
"name": "ZYTX",
"age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
"gender": "AAAAAA.doc"
}, {
"name": "ZYTA",
"age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
"gender": "BBBBBB.doc"
}, {
"name": "ZDTX",
"age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
"gender": "CCCCCC.doc"
}, {
"name": "ZYTX",
"age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
"gender": "AAAAAA.doc"
}];
var hash = {};
arr = arr.reduce(function(item, next) {
hash[next.name] ? '' : hash[next.name] = true && item.push(next);
return item
}, [])
console.log(arr);

posted @ 2017-08-10 16:48  漆黑小T  阅读(257)  评论(0编辑  收藏  举报