Rog*_*rHN 0 javascript arrays sorting count
我试图找到一种方法来计算我在这个数组中每种类型的条目数:
var types = [
"loc_67249556",
"loc_52558678",
"loc_62658330",
"gra_59669755",
"gra_59289309"
]
Run Code Online (Sandbox Code Playgroud)
我所说的"类型"是每个条目的3个首字母.我使用for来遍历数组并提取3个首字母:
for (var i = 0; i < types.length; k++) {
var tp= types[k].split('_');
tp = tp[0];
}
Run Code Online (Sandbox Code Playgroud)
这将输出3个首字母,但我如何计算它们并以一种我以后可以使用它的方式保存?
类似于具有类型的新数组以及它们出现在第一个数组中的次数,类似于:
var types_count = [
{
type: "loc",
qnt: 3
},
{
type: "gra",
qnt: 2
}
]
Run Code Online (Sandbox Code Playgroud)
另外,我总共拥有的"类型"是51种不同类型的条目,所有条目都以3个字母开头.
使用reduce以提取前3个字母,加入到由类型索引的蓄能器对象,然后得到该对象的值:
const types = [
"loc_67249556",
"loc_52558678",
"loc_62658330",
"gra_59669755",
"gra_59289309"
];
const typeCount = types.reduce((a, str) => {
const type = str.slice(0, 3);
if (!a[type]) a[type] = { type, count: 0 };
a[type].count++;
return a;
}, {})
console.log(Object.values(typeCount));Run Code Online (Sandbox Code Playgroud)