Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- const _ = require( 'lodash' );
- const mixins = {
- /**
- * Return a new array containing only the unique objects inside the provided
- * array. Unlike _.uniq, this will check _every_ key/value in the array
- *
- * @param {Array} arr Array of structurally identical objects
- * @return {Array}
- * @example
- *
- * const objs = [ { x: 1, y: 2 }, { a: 1, b: 2 }, { x: 1, y: 2 }];
- *
- * console.log( _( objs ).uniqObjs().value() )
- * console.log( _.uniqObjs( objs ) )
- *
- * // => [ { x: 1, y: 2 }, { a: 1, b: 2 } ]
- */
- uniqObjs: arr => {
- // Make sure that the arr parameter is a defined & populated array of objects
- if( _.isUndefined( arr ) || ! _.isArray( arr ) || ! arr.length || ! _.isObject( arr[0] ) )
- return false;
- const uniqs = [];
- // Filter out the duplicate objects within the array by checking if
- // the stringified object value already exist in the temporary uniqs
- // array (while adding them to the variable)
- return _.filter( arr, ( obj ) => {
- // Use _.sortObj to sort the contents of the object by the keys, since stringify
- // will use the current order (which means identical objects in different orders
- // will be seen as discrepancies)
- if( _.indexOf( uniqs, JSON.stringify( mixins.sortObj( obj ) ) ) === -1 ){
- uniqs.push( JSON.stringify( mixins.sortObj( obj ) ) );
- return true;
- }
- return false;
- });
- },
- /**
- * Return a copy of the object with the content sorted by the keys
- *
- * @param {Object} obj Object to sort by keys
- * @return {Object}
- * @example
- *
- * const obj = {c:1, b:2, a:3};
- *
- * console.log( _.sortObj( obj ) );
- * console.log( _( obj ).sortObj().value() );
- *
- * // => { a: 3, b: 2, c: 1 }
- */
- sortObj: obj => {
- const result = {};
- _( obj ).
- keys( )
- .sort()
- .forEach( ( v, i ) => {
- result[ v ] = obj[ v ];
- })
- .commit();
- return result;
- }
- };
- _.mixin( mixins );
- module.exports = _;
Advertisement
Add Comment
Please, Sign In to add comment