1.1.2 • Published 5 years ago

arr-filter-unique v1.1.2

Weekly downloads
7
License
ISC
Repository
github
Last release
5 years ago

💡 Filter unique elements in arrays!

function arrFilterUnique(array, key = undefined)

Usage

Simplest use:

const arrFilterUnique = require('arr-filter-unique');
// For typescript use: import * as arrFilterUnique from 'arr-filter-unique';

arrFilterUnique([1, 1, 2, 3, 3, 4, 5, 5]);
// [1, 2, 3, 4, 5]

Filter elements by id:

arrFilterUnique([{ id: 1 }, { id: 1 }, { id: 2 }], 'id');
// [{id: 1}, {id: 2}]

Filter by a deeper property:

const movies = [
  {
    title: 'Pretty Woman',
    starring: {
      name: 'Julia',
      lastname: 'Roberts'
    },
  {
    title: '17 Again',
    starring: {
      name: 'Matthew',
      lastname: 'Perry'
    },
  {
    title: 'The Smurfs',
    starring: {
      name: 'Katy',
      lastname: 'Perry'
    }
];

const uniqueLastnameMovies = arrFilterUnique(movies, 'starring.lastname');
// [{
// title: 'Pretty Woman',
// starring: {
//   name: 'Julia',
//   lastname: 'Roberts'
// },
// {
// title: '17 Again',
// starring: {
//   name: 'Matthew',
//   lastname: 'Perry'
// }]


// Now I would just want the lastnames:
const uniqueLastnames = uniqueLastnameMovies.map(movie => movie.starring.lastname);
// ['Roberts', 'Perry']

API

ParameterTypeNeededDescription
arrayany[]yesThe array to filter
keystringnoIf provided, objects are compared by this key. Can use dot notation: path.to.identifying.key

Returns: The filtered array with no repeated elements (according to the identifying key passed).

Contribute

Hope this helps you. Feel free to clone and send PR 🙂

Credits

Raschid JF. Rafaelly

me@raschidjfr.dev

https://raschidjfr.dev