删除对象数组中的重复元素

语法

  1. import { arrObjectWithoutDupli } from 'warbler-js';
  2. const result = arrObjectWithoutDupli(arrkey)

参数

  • arr (Array) : 要去重的数组。
  • key (String) : 根据对象的 key 去重。

返回值

Array : 返回一个去重后的新数组。

源码

  1. const obj = {};
  2. const arrObjectWithoutDupli = (arr, key) =>
  3. arr.reduce((cur, next) => {
  4. if (!obj[next[key]]) {
  5. obj[next[key]] = cur.push(next);
  6. }
  7. return cur;
  8. }, []);

例子

  1. import { arrObjectWithoutDupli } from 'warbler-js';
  2. const fruits = [
  3. { name: 'Grapes', quantity: 2 },
  4. { name: 'Bananas', quantity: 5 },
  5. { name: 'Apples', quantity: 10 },
  6. { name: 'Grapes', quantity: 4 },
  7. { name: 'Grapes', quantity: 6 },
  8. ];
  9. const result = arrObjectWithoutDupli(fruits, 'name');
  10. console.log(result); // =>
  11. // [
  12. // {name: 'Grapes', quantity: 2},
  13. // {name: 'Bananas', quantity: 5},
  14. // {name: 'Apples', quantity: 10},
  15. // ];