Last active
March 1, 2018 07:33
-
-
Save tbekaert/54a3cec1b3c413cd6486c123a4d0a9a1 to your computer and use it in GitHub Desktop.
Collection of js utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Concat arrays | |
* | |
* @params {array} arrs - List of arrays | |
* @example | |
* import { concatArrays } from "path/to/array.js" | |
* | |
* let arr1 = [1, 2, 3]; | |
* let arr2 = [4, 5, 6]; | |
* | |
* concatArrays(arr1, arr2, [7, 8, 9, 2, 4]); | |
* // Return [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] | |
*/ | |
export let concatArrays = (...arrs) => [].concat(...arrs); | |
/** | |
* Remove duplicates from simple arrays | |
* | |
* @params {array} arrs - List of arrays | |
* @example | |
* import { uniqueArray } from "path/to/array.js" | |
* | |
* uniqueArray([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 4 ]); | |
* // Return [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] | |
*/ | |
export let uniqueArray = arr => [...new Set(arr)]; | |
/** | |
* Remove duplicates objects in array base on an object key | |
* | |
* @params {string} p - Key to look for in each object | |
* @params {array} arr - Array | |
* @example | |
* import { unitArrayObjects } from "path/to/array.js" | |
* | |
* let arr = [ | |
* { id: 6, username: 'lorem' }, | |
* { id: 8, username: 'ipsum' }, | |
* { id: 6, username: 'lorem' }, | |
* { id: 7, username: 'dolor' } | |
* ]; | |
* | |
* uniqueArrayObjects('id', arr); | |
* // | |
* Return : | |
* [ | |
* { id: 6, username: 'lorem' }, | |
* { id: 8, username: 'ipsum' }, | |
* { id: 7, username: 'dolor' } | |
* ] | |
*/ | |
export let uniqueArrayObjects = (p, arr) => arr.reduce((a, b) => !a.filter(c => b[p] === c[p]).length ? [...a, b] : a, []); | |
/** | |
* Remove duplicates objects in array with deep comparison | |
* | |
* @params {array} arr - Array | |
* @example | |
* import { unitArrayObjectsDeep } from "path/to/array.js" | |
* | |
* let arr = [ | |
* { id: 6, username: 'lorem' }, | |
* { id: 8, username: 'ipsum' }, | |
* { id: 6, username: 'dolor' }, | |
* { id: 7, username: 'sit' }, | |
* { id: 8, username: 'ipsum' }, | |
* ]; | |
* | |
* uniqueArrayObjectsDeep('id', arr); | |
* // | |
* Return : | |
* [ | |
* { id: 6, username: 'lorem' }, | |
* { id: 8, username: 'ipsum' }, | |
* { id: 6, username: 'dolor' }, | |
* { id: 7, username: 'sit' } | |
* ] | |
*/ | |
export let uniqueArrayObjectsDeep = arr => uniqueArray( arr.map(a => JSON.stringify(a)) ).map(a => JSON.parse(a)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment