Home > Article > Web Front-end > Analysis of JavaScript repeated element processing methods [statistical number, calculation, deduplication, etc.]_javascript skills
This article mainly introduces the JavaScript repeated element processing method, combined with the example form to analyze javascript the number statistics, calculation and deduplication of repeated elements in strings and arrays For related operating techniques, friends who are interested in JavaScript can refer to
. This article describes how to handle repeated elements in JavaScript with examples. Share it with everyone for your reference, the details are as follows:
Determine the character that appears most often in a string, and count the number
//将字符串的字符保存在一个hash table中,key是字符,value是这个字符出现的次数 var str = "abcdefgaddda"; var obj = {}; for (var i = 0, l = str.length; i < l; i++) { var key = str[i]; if (!obj[key]) { obj[key] = 1; } else { obj[key]++; } } /*遍历这个hash table,获取value最大的key和value*/ var max = -1; var max_key = ""; var key; for (key in obj) { if (max < obj[key]) { max = obj[key]; max_key = key; } } alert("max:"+max+" max_key:"+max_key);
Written by A method to find the byte length of a string
Assumption:
One English character occupies one byte, and one Chinese character occupies two bytes
function GetBytes(str){ var len = str.length; var bytes = len; for(var i=0; i<len; i++){ if (str.charCodeAt(i) > 255) bytes++; } return bytes; } alert(GetBytes("你好,as"));
Write a method to remove duplicate elements from an array
var arr = [1 ,1 ,2, 3, 3, 2, 1]; Array.prototype.unique = function(){ var ret = []; var o = {}; var len = this.length; for (var i=0; i<len; i++){ var v = this[i]; if (!o[v]){ o[v] = 1; ret.push(v); } } return ret; }; alert(arr.unique());
Write a method to remove all duplicate elements from a string
var arr = '112332454678'; String.prototype.unique = function(){ var ret = []; var o = {}; var len = this.length; for (var i=0; i<len; i++){ var v = this[i]; if (!o[v]){ o[v] = 1; } else { o[v] = 2; } } for(var k in o){ if (o[k]==1) { ret.push(k); }; } return ret; }; alert(arr.unique());
PS: Here are several deduplication tools for your reference:
Online duplicate removal tool:
http://tools.jb51.net/code/quchong
Online Text deduplication tool:
http://tools.jb51.net/aideddesign/txt_quchong
The above is all the content of this article, I hope it can be Bringing help to everyone! !
Related recommendations:
Detailed explanation of JavaScript facade pattern
Scope and block-level scope in Javascript
The above is the detailed content of Analysis of JavaScript repeated element processing methods [statistical number, calculation, deduplication, etc.]_javascript skills. For more information, please follow other related articles on the PHP Chinese website!