const people = [ {name: 'test1', age: 25, sex:'male', tel: '17853538076', address: { provice: '山东省', city: '聊城市' }}, {name: 'test2', age: 23, sex:'female', tel: '17853538071', address: { provice: '山东省', city: '烟台市' }}, {name: 'test3', age: 22, sex:'male', tel: '17853538072', address: { provice: '山东省', city: '聊城市' }}, {name: 'test4', age: 25, sex:'female', tel: '17853538073', address: { provice: '山东省', city: '聊城市' }}, {name: 'test5', age: 22, sex:'male', tel: '17853538077', address: { provice: '山东省', city: '烟台市' }} ] function groupBy(arr, generateKey) { if (typeof generateKey === 'string') { const propName = generateKey; generateKey = (item) => item[propName]; } const result = {}; for (const item of arr) { const key = generateKey(item); if (!result[key]) { result[key] = []; } result[key].push(item); } return result; }
groupBy(people, 'age');
groupBy(people, (item) => `${item.age}-${item.sex}`);
groupBy(people, (item) => item.address.provice);
groupBy(people, (item) => item.address.city);
|