distinct_by

Modified on Thu, 9 Jul at 10:49 AM

distinct_by

TABLE OF CONTENTS

Get unique items from an array based on a property

Definition

array distinct_by(array $input, &key_function)

From an $input array, removes all the objects that have a non-unique value of $key_function. The first unique entry is kept.

Parameters

array $input

Array of objects to check for duplicates.

string $key_function

A key of the objects in the array. Only one object will be preserved with each key value.

Returns

array

Array obtained by removing all duplicate objects by $key_function from the $input array.

Examples

Sample data
{
  "inputA":[
   {"name":"Bob","id":0},
   {"name":"Ann","id":0},
   {"name":"Joe","id":1},
   {"name":"Xavier","id":1}
  ],
  "inputB":[
    {"name":"Bob","id":null},
    {"name":"Ann","id":0},
    {"name":"Joe"},
    {"name":"Xavier","id":1}
  ]
}
Transformation
{ 
  a: distinct_by(inputA, &id),
  b: distinct_by(inputB, &id),        // Warning: id not present in some elements
  emptyArray: distinct_by(`[]`, &id),
  null: distinct_by(`null`, &id),
  object: distinct_by(`{}`, &id)      // Error
}
Result
{
  "a":[{"name":"Bob","id":0},{"name":"Joe","id":1}],
  "b":[{"name":"Ann","id":0},{"name":"Xavier","id":1}],
  "emptyArray":[],
  "null":null
}

Remarks

  • A warning is raised if some objects don't have the $key_function key.
  • The objects that don't have the $key_function key, or its value on them is null, are removed from the array.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article