在数组中查找唯一对象

Noe*_*les 5 javascript arrays object lodash

我有一个数组如下:

const arr = [
            {company: 'a', date: '1'},
            {company: 'b', date: '1'},
            {company: 'c', date: '1'},
            {company: 'a', date: '2'},
            {company: 'a', date: '1'},
            {company: 'b', date: '2'},
          ]
Run Code Online (Sandbox Code Playgroud)

我只想知道如何在其中获取独特的对象。我尝试通过以下命令使用 lodash:

uniqBy(arr, 'date');
Run Code Online (Sandbox Code Playgroud)

但它只返回:

[
  {company: "a", date: "1"},
  {company: "a", date: "2"}
]
Run Code Online (Sandbox Code Playgroud)

我想要这样的东西:

[
  {company: "a", date: "1"},
  {company: "a", date: "2"},
  {company: "b", date: "1"},
  {company: "b", date: "2"},
  {company: "c", date: "1"},
]

Run Code Online (Sandbox Code Playgroud)

在 lodash 或 vanilla JS 中有没有办法做到这一点?

Mah*_*Ali 6

reduce()在纯 js 的帮助下,我创建了一个函数,该函数将对象数组和键数组作为输入,并返回所有这些键唯一的数组。

以下是算法的步骤:

  • 首先,我们需要使用reduce().
  • key对象的 将是所需键的值,每个键都由-(我keyString在代码注释中为每个对象提到过)提供。
  • 将具有相同的对象keyString意味着给定数组的相同值keys只会自动出现一次,因为对象不能有重复的键
  • 最后我们使用Object.values()to 创建一个数组。

const arr = [
            {company: 'a', date: '1'}, //keyString = "a-1"
            {company: 'b', date: '1'}, //keyString = "b-1"
            {company: 'c', date: '1'}, //keyString = "c-1"
            {company: 'a', date: '2'}, //keyString = "a-2"
            {company: 'a', date: '1'}, //keyString = "a-1"
            {company: 'b', date: '2'}, //keyString = "b-2"
            //The item at index 0 and index 4 have same keyString so only a single of them will remain in object.
          ] 

const uniqueBy = (arr, keys) => {
  const obj = arr.reduce((ac, a) => {
    let keyString = keys.map(k => a[k]).join('-');
    ac[keyString] = a;
    return ac;
  }, {});
  return Object.values(obj);
}

console.log(uniqueBy(arr, ['company', 'date']))
Run Code Online (Sandbox Code Playgroud)


Dim*_*ias 5

这个 lodash 函数组合应该这样做:

_.uniqWith(arr, _.isEqual);
Run Code Online (Sandbox Code Playgroud)

如果您只想考虑唯一性的属性组合而将其他属性排除在外,您可以使用 uniqBy() 和您自己的自定义函数来设置标准。例如:

const arr = [
            {company: 'a', date: '1', clients: 3},
            {company: 'b', date: '1', clients: 2},
            {company: 'c', date: '1', clients: 2},
            {company: 'a', date: '1', clients: 1}
          ]

const uniqArr = _.uniqBy(arr, function(obj){
  return obj.company + obj.date;
});

// => [
       {company: 'a', date: '1', clients: 3},
       {company: 'b', date: '1', clients: 2},
       {company: 'c', date: '1', clients: 2}
      ]
Run Code Online (Sandbox Code Playgroud)

在本例中,client 属性不影响唯一性,因此将排除最后一个对象,因为 company 和 date 属性与第一个对象相同。