我有一个字符串数组:
var array = ['bob', 'charlie', 'bob', 'bob'];
我想删除重复项,然后我想将它转换为一个对象数组,同时添加一个重复的计数属性。
这就是我想要实现的目标:
var filteredData = [{ name: 'bob', count: 3}, { name: 'charlie', count: 1}];
我该怎么做?
答案 0 :(得分:3)
Ecmascript5 解决方案:
var arr = ['bob', 'charlie', 'bob', 'bob'],
counts = arr.reduce(function(r,s){
(!r[s])? r[s] = {name: s, count: 1} : r[s]['count']+=1;
return r;
}, {}),
result = Object.keys(counts).map(function(k){ return counts[k]; });
console.log(result);
Ecmascript6 版本(带Object.values()功能):
var arr = ['bob', 'charlie', 'bob', 'bob'],
result = Object.values(arr.reduce((r,s) => {
(!r[s])? r[s] = {name: s, count: 1} : r[s]['count']+=1;
return r;
}, {}));
console.log(result);
答案 1 :(得分:0)
将Map与Array#reduce
一起使用:
const array = ['bob', 'charlie', 'bob', 'bob'];
const result = [...array.reduce((map, name) => {
const current = map.get(name) || { name, count: 0 };
current.count++;
return map.set(name, current);
}, new Map()).values()];
console.log(result);

答案 2 :(得分:0)
以下是Array.prototype.reduce的简单用法:
const data = ['bob', 'charlie', 'bob', 'bob']
const result = data.reduce(function(prev, curr) {
const index = prev.findIndex(el => el.name === curr)
if (index !== -1) {
prev[index].count += 1
} else {
prev.push({ name: curr, count: 1 })
}
return prev
}, [])
console.log(result)