# 删除对象数组中的重复元素
# 语法
import { arrObjectWithoutDupli } from 'jtoolset';
const result = arrObjectWithoutDupli(arr,key)
# 参数
arr
(Array) : 要去重的数组。key
(String) : 根据对象的key
去重。
# 返回值
Array : 返回一个去重后的新数组。
# 源码
const obj = {};
const arrObjectWithoutDupli = (arr, key) =>
arr.reduce((cur, next) => {
if (!obj[next[key]]) {
obj[next[key]] = cur.push(next);
}
return cur;
}, []);
# 例子
import { arrObjectWithoutDupli } from 'jtoolset';
const fruits = [
{ name: 'Grapes', quantity: 2 },
{ name: 'Bananas', quantity: 5 },
{ name: 'Apples', quantity: 10 },
{ name: 'Grapes', quantity: 4 },
{ name: 'Grapes', quantity: 6 },
];
const result = arrObjectWithoutDupli(fruits, 'name');
console.log(result); // =>
// [
// {name: 'Grapes', quantity: 2},
// {name: 'Bananas', quantity: 5},
// {name: 'Apples', quantity: 10},
// ];