根据 JavaScript/jQuery 中的计数将数组转换为子数组?
Convert array to sub arrays based on their count in JavaScript/jQuery?
如何根据 JavaScript 或 jQuery 中的元素值计数将我的数组转换为子数组?
例如:
var myArray=["a","b","c","a","a","c","b"];
计算元素a、b、c后的预期输出
outputArray=[["a",3],["b",2],["c",2]];
您可以使用 reduce()
和 ES6 Map()
并传播语法 ...
.
var myArray=["a","b","c","a","a","c","b"];
var result = [...myArray.reduce(function(r, e) {
return r.set(e, !r.get(e) ? 1 : r.get(e) + 1)
}, new Map())]
console.log(result)
如果您想以自己的方式解决问题而不是尝试
var myArray=["a","b","c","a","a","c","b"];
var obj = [];
for (var i = 0, j = myArray.length; i < j; i++) {
obj[myArray[i]] = (obj[myArray[i]] || 0) + 1;
}
var finalArr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var arr = [];
arr.push(key);
arr.push(obj[key]);
finalArr.push(arr);
}
}
console.log(finalArr);
function countLetters(arr) {
return arr.reduce(function(r, e) {
r[e] = (r[e] || 0) + 1;
return r;
}, {});
}
另一种方法
如何根据 JavaScript 或 jQuery 中的元素值计数将我的数组转换为子数组?
例如:
var myArray=["a","b","c","a","a","c","b"];
计算元素a、b、c后的预期输出
outputArray=[["a",3],["b",2],["c",2]];
您可以使用 reduce()
和 ES6 Map()
并传播语法 ...
.
var myArray=["a","b","c","a","a","c","b"];
var result = [...myArray.reduce(function(r, e) {
return r.set(e, !r.get(e) ? 1 : r.get(e) + 1)
}, new Map())]
console.log(result)
如果您想以自己的方式解决问题而不是尝试
var myArray=["a","b","c","a","a","c","b"];
var obj = [];
for (var i = 0, j = myArray.length; i < j; i++) {
obj[myArray[i]] = (obj[myArray[i]] || 0) + 1;
}
var finalArr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var arr = [];
arr.push(key);
arr.push(obj[key]);
finalArr.push(arr);
}
}
console.log(finalArr);
function countLetters(arr) {
return arr.reduce(function(r, e) {
r[e] = (r[e] || 0) + 1;
return r;
}, {});
}
另一种方法