如何使用JavaScript实现查找数组("a","x","b","d","m","a","k","m","p","j","a")
2个回答
展开全部
var arr = ["a","x","b","d","m","a","k","m","p","j","a","m"];
var ret = {};
var res = [];
var res2 = [];
var max;
for(var i = 0; i < arr.length; i++) {
var item = arr[i];
if(!ret[item]) {
ret[item] = {};
ret[item][item] = item;
ret[item].count = 1;
ret[item].index = [];
ret[item].index.push(i);
} else {
ret[item].count++;
ret[item].index.push(i);
}
}
for(var i in ret) {
var item = ret[i];
res.push(item);
}
//按重复次数排序
res.sort(function(a,b) {
return a.count - b.count < 0;
});
for(var i = 0; i < res.length - 1; i++) {
if(i === 0) {
max = res[i].count;
}
if(res[i].count === max) {
res2.push(res[i]);
}
}
//得到出现次数最多的字母数组
console.log(res2);
结果:
[
{
a: "a", //字母
count: 3, //重复次数
index: [0, 5, 10] //出现下标
},
{
count: 3,
index: [4, 7, 11],
m: "m"
}
]
追问
原理知道了,谢谢。。开始就是不知道原理,,搞了半天,,,
展开全部
//以下代码纯手打,望采纳
var arr = ["a", "x", "b", "d", "m", "a", "k", "m", "p", "j", "a"];
//循环外声明变量,避免重复申明变量,减少内存开销,
//result 和 obj 的格式在下面有说明
var result = {}, info, obj;
for (var i = 0; i < arr.length; i++) {
//初始化obj对象,result中有记录则取result中的对象,无则新建空对象
info = arr[i], obj = result[info] || {}, obj.idx = obj.idx || [];
//对元素出现的次数进行累加,并保存索引
obj.cnt = ~~obj.cnt + 1, obj.idx.push(i);
//将新结构保存在result中
result[info] = obj;
}
/*
*得到结果如下
* idx表示出现过的索引,是数组
* cnt表示出现的次数
result = {
"a":{"idx":[0,5,10],"cnt":3},
"x":{"idx":[1],"cnt":1},
"b":{"idx":[2],"cnt":1},
"d":{"idx":[3],"cnt":1},
"m":{"idx":[4,7],"cnt":2},
"k":{"idx":[6],"cnt":1},
"p":{"idx":[8],"cnt":1},
"j":{"idx":[9],"cnt":1}
}
*/
//这里就是循环找到cnt最大的对象,细节就不说了,maxObj就是你要的
//ps:如果数据出现两个或者多个最大值,我这里是优先找到第一个
var maxObj,obj;
for (var k in result){
obj = result[k];
if (!maxObj || ~~obj.cnt > ~~maxObj.cnt) {
maxObj = obj;
maxObj.key = k;
}
}
//结果:maxObj = {"idx":[0,5,10],"cnt":3,"key":"a"}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询