You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.6 KiB

4 years ago
  1. # `unique()`
  2. The unique method returns all of the unique items in the collection:
  3. ```js
  4. const collection = collect([1, 1, 1, 2, 3, 3]);
  5. const unique = collection.unique();
  6. unique.all();
  7. // [1, 2, 3]
  8. ```
  9. When dealing with an array of objects, you may specify the key used to determine uniqueness:
  10. ```js
  11. const collection = collect([
  12. { name: 'iPhone 6', brand: 'Apple', type: 'phone' },
  13. { name: 'iPhone 5', brand: 'Apple', type: 'phone' },
  14. { name: 'Apple Watch', brand: 'Apple', type: 'watch' },
  15. { name: 'Galaxy S6', brand: 'Samsung', type: 'phone' },
  16. { name: 'Galaxy Gear', brand: 'Samsung', type: 'watch' },
  17. ]);
  18. const unique = collection.unique('brand');
  19. unique.all();
  20. // [
  21. // { name: 'iPhone 6', brand: 'Apple', type: 'phone' },
  22. // { name: 'Galaxy S6', brand: 'Samsung', type: 'phone' },
  23. // ]
  24. ```
  25. You may also pass your own callback to determine item uniqueness:
  26. ```js
  27. const collection = collect([
  28. { name: 'iPhone 6', brand: 'Apple', type: 'phone' },
  29. { name: 'iPhone 5', brand: 'Apple', type: 'phone' },
  30. { name: 'Apple Watch', brand: 'Apple', type: 'watch' },
  31. { name: 'Galaxy S6', brand: 'Samsung', type: 'phone' },
  32. { name: 'Galaxy Gear', brand: 'Samsung', type: 'watch' },
  33. ]);
  34. const unique = collection.unique(item => item.brand + item.type);
  35. unique.all();
  36. // [
  37. // { name: 'iPhone 6', brand: 'Apple', type: 'phone' },
  38. // { name: 'Apple Watch', brand: 'Apple', type: 'watch' },
  39. // { name: 'Galaxy S6', brand: 'Samsung', type: 'phone' },
  40. // { name: 'Galaxy Gear', brand: 'Samsung', type: 'watch' },
  41. // ]
  42. ```
  43. [View source on GitHub](https://github.com/ecrmnn/collect.js/blob/master/src/methods/unique.js)