Skip to content

Instantly share code, notes, and snippets.

@DefectingCat
Last active April 21, 2022 07:44
Show Gist options
  • Save DefectingCat/50f661bd8a69068170988c3811f39bf0 to your computer and use it in GitHub Desktop.
Save DefectingCat/50f661bd8a69068170988c3811f39bf0 to your computer and use it in GitHub Desktop.
数组去重合并
let arr = [
{ name: 'zs', age: 15, happy: ['唱歌', '玩游戏'] },
{ name: 'ls', age: 15, happy: ['玩游戏'] },
{ name: 'zs', age: 15, happy: ['学习', '划水'] },
];
function test(arr) {
let _obj = {};
let _arr = [];
if (!arr.length) return;
arr.map((item) => {
_obj[item.name]?.happy.length
? (_obj[item.name].happy = [..._obj[item.name].happy, ...item.happy])
: (_obj[item.name] = item);
});
_arr = Object.values(_obj);
return _arr;
}
let arr2 = test(arr);
console.log(arr2);
let arr = [
{ name: 'zs', age: 15, happy: ['唱歌', '玩游戏'] },
{ name: 'ls', age: 15, happy: ['玩游戏'] },
{ name: 'zs', age: 15, happy: ['学习', '划水'] },
];
function test(arr) {
let _obj = {};
let _arr = [];
if (arr.length)
arr.map((item) => {
_obj[item.name]?.happy.length
? (_obj[item.name].happy = _obj[item.name].happy.concat(item.happy))
: (_obj[item.name] = item);
});
_arr = Object.values(_obj);
return _arr;
}
let arr2 = test(arr);
console.log(arr2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment