Skip to content
大纲

删除对象数组中指定属性值重复的元素

语法

js
import { arrObjectWithoutDupli } from 'warbler-js';
const result = arrObjectWithoutDupli(arr,key)

参数

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

返回值

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

源码

js
const arrObjectWithoutDupli = (arr, key) => {
  const obj = {};
  return arr.reduce((cur, next) => {
    if (!obj[next[key]]) {
      obj[next[key]] = cur.push(next);
    }
    return cur;
  }, []);
};

例子

js
import { arrObjectWithoutDupli } from 'warbler-js';
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},
// ];

添加版本

1.2.0

Released under the MIT License.