我有一个数组中的项目列表,我想创建一个新数组,该数组是一个对象数组,其中键是现有数组的值,值是该项目在现有数据中的次数阵列。希望这样做,如果没有希望这个例子会有所帮助。没有像lodash或下划线那样的第三方图书馆。
非常感谢任何帮助,谢谢。
var arr = [a,a,a,b,c,c,d,e,f,f,f,f];
new array =[{a:3},{b:1},{c:2},{d:1},{e:1},{f:4}];
到目前为止我的尝试:
countryCodes.sort();
var result = count(countryCodes);
console.log(result[0]+": "+result[1]);
function count(arr) {
var a = [], b = [], prev;
arr.sort();
for ( var i = 0; i < arr.length; i++ ) {
if ( arr[i] !== prev ) {
a.push(arr[i]);
b.push(1);
} else {
b[b.length-1]++;
}
prev = arr[i];
}
return [a, b];
}
答案 0 :(得分:2)
你很亲密。
var a = "aa",
b = "bb",
c = "cc",
d = "dd",
e = "ee",
f = "ff";
var arr = [a,a,a,b,c,c,d,e,f,f,f,f];
function getCount(arr) {
var result = {};
for (var val of arr) result[val] = result[val] + 1 || 1;
return result;
}
var totals = getCount(arr);
document.write(JSON.stringify(totals));
答案 1 :(得分:1)
按console
按钮时打开run
。
var arr = ['a', 'a', 'a', 'b', 'c', 'c', 'd', 'e', 'f', 'f', 'f', 'f'];
function getObjectFromArray(a) {
var result = [],
alreadyAdded = [];
a.forEach(function(item) {
var key = item,
obj = {};
if (alreadyAdded.indexOf(item) != -1) return;
alreadyAdded.push(item)
obj[key] = getCount(a, item)
result.push(obj)
})
return result;
}
function getCount(a, el) {
var count = 0;
a.forEach(function(element) {
if (element == el) count++
})
return count;
}
console.log(getObjectFromArray(arr))
&#13;
答案 2 :(得分:1)
这是另一种工作方式。
function count(arr) {
var prev = arr[0];
var current;
var newArr = [];
var count = 0;
var obj = {};
for (var i = 0; i < arr.length; i++) {
current = arr[i];
if (i == arr.length - 1) {
if (prev == current) {
count++;
obj = {};
obj[prev] = count;
newArr.push(obj);
}
else {
obj = {};
obj[prev] = count;
newArr.push(obj);
count = 1;
obj = {};
obj[current] = count;
newArr.push(obj);
}
}
else if (prev == current) {
count++;
}
else {
obj = {};
obj[prev] = count;
newArr.push(obj);
count = 1;
prev = current;
}
}
return newArr;
}
console.log(count(['a', 'a', 'a', 'b', 'c', 'c', 'd', 'e', 'f', 'f', 'f', 'f']));
答案 3 :(得分:1)
使用Array.prototype.reduce()
var arr = ["a","a","a","b","c","c","d","e","f","f","f","f"],
res = arr.reduce((p,c) => { var i = p.findIndex(e => !!e[c]);
!!~i ? p[i][c]++ : p.push({[c]:1});
return p},[]);
document.write("<pre>" + JSON.stringify(res) + "</pre>");
&#13;
好的,下面的一个应该像o(2n)一样快,并且它不会比两行对象分配更长。
var arr = ["a","a","a","b","c","c","d","e","f","f","f","f"],
mid = arr.reduce((p,c) => {!!p[c] ? p[c]++ : p[c]=1; return p},{}),
res = Object.keys(mid).map(e => ({[e]:mid[e]}));
document.write("<pre>" + JSON.stringify(res) + "</pre>");
&#13;