Michael Profile Picture
Michael Malura
Entwickler - Fotograf - Technologie-Enthusiast

Ramda - Find duplicates in an array of objects

05.11.2018 code , ramda , javascript

For my current project i need to verify that a list of transactions doesn't contain any duplicates based on the transaction id.

Dataset

My data looks something like this.

const data = {
  'transactions': [{
    'transaction': 'A', // This field must be unique inside the whole array
    'events': [{
      'number': 0
    }, {
      'number': 1
    }]
  }, {
    'transaction': 'B', // <--
    'events': [{
      'number': 0,
    }, {
      'number': 1,
    }]
  }]
};

Code

const { transactions } = data;
const hasDuplicates = R.pipe(
 R.groupBy(R.prop('transaction')), // Group transactions by their id
 R.mapObjIndexed(R.prop('length')), // Get an object of id and length of transactions with this id
 R.values, // Only get the number of elements in every array
 R.any(R.lte(2)) // Check if 2 is smaller than any element in the array
);

hasDuplicates(transactions);