3 回答
TA贡献1772条经验 获得超5个赞
var arr = [
{ id:1 , name:'a', title: 'qmummbw' },
{ id:2 , name:'b', title: 'sdmus' },
{ id:2 , name:'', title: 'dvfv' },
{ id:3 , name:'c', title: 'dujuw' },
{ id:1 , name:'d', title: 'ccnyu' },
{ id:4 , name:'e', title: 'tjtjn' },
{ id:4 , name:'f', title: 'tryr' },
{ id:1 , name:'g', title: 'gbgfbgf' },
{ id:2 , name:'h', title: 'tgrtg' },
{ id:3 , name:'i', title: 'fdvd' },
{ id:1 , name:'j', title: 'dsnyc' },
{ id:1 , name:'k', title: 'nyuny' }
],
result = Object.values(arr.reduce(function (r, a) {
r[a.id] = r[a.id] || [];
r[a.id].push(a);
return r;
}, Object.create(null))).map(e => e);
console.log([result]);
TA贡献1856条经验 获得超5个赞
id如有必要,您可以分组并从对象中获取值。
const
array = [{ id: 1 , name: 'a', title: 'qmummbw' }, { id: 2 , name: 'b', title: 'sdmus' }, { id: 2 , name: '', title: 'dvfv' }, { id: 3 , name: 'c', title: 'dujuw' }, { id: 1 , name: 'd', title: 'ccnyu' }, { id: 4 , name: 'e', title: 'tjtjn' }, { id: 4 , name: 'f', title: 'tryr' }, { id: 1 , name: 'g', title: 'gbgfbgf' }, { id: 2 , name: 'h', title: 'tgrtg' }, { id: 3 , name: 'i', title: 'fdvd' }, { id: 1 , name: 'j', title: 'dsnyc' }, { id: 1 , name: 'k', title: 'nyuny' }],
grouped = array.reduce((r, o) => ((r[o.id] = r[o.id] || []).push(o), r), {});
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
举报