Skip to content

Instantly share code, notes, and snippets.

@matsuby
Last active October 18, 2018 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsuby/9f2490bfc9337cec0cfd9dd585313580 to your computer and use it in GitHub Desktop.
Save matsuby/9f2490bfc9337cec0cfd9dd585313580 to your computer and use it in GitHub Desktop.
JavaScript one-liner function: groupArr2d and groupConcatArr2d (>=ES2017)
// for ES2017
{
const groupArr2d = (arr2d, {swap=false} = {}) => arr2d.reduce((a,c)=>Object.assign(a,{[c[+swap]]:a[c[+swap]]?[...a[c[+swap]],c[+!swap]]:[c[+!swap]]}),{});
const groupConcatArr2d = (arr2d, {swap=false, glue=","} = {}) => Object.assign({},...Object.entries(arr2d.reduce((a,c)=>Object.assign(a,{[c[+swap]]:a[c[+swap]]?[...a[c[+swap]],c[+!swap]]:[c[+!swap]]}),{})).map(e=>({[e[0]]:e[1].join(glue)})));
// two-dimensional arrays can represent object.
// in each array, the first value can be regarded as a key, and the next value can be regarded as a value.
// `Object.entries(obj)` is easy to understand as an example.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries#Examples
const testArr2d = [
["sameKey","anotherValue1"],
["sameKey","anotherValue2"],
["anotherKey1","sameValue"],
["anotherKey2","sameValue"],
];
/*=========================================
* groupArr2d test
*=======================================*/
// get object: {key: array of value that grouped by key}
console.log(groupArr2d(testArr2d));
// get object: {value: array of key that grouped by value}
console.log(groupArr2d(testArr2d, {swap: true}));
/*=========================================
* groupConcatArr2d test
*=======================================*/
// get object: {key: concat value string with ","(default glue) that grouped by key}
console.log(groupConcatArr2d(testArr2d));
// get object: {value: concat key string with ","(default glue) that grouped by value}
console.log(groupConcatArr2d(testArr2d, {swap: true}));
// get object: {key: concat value string with "|glue|"(specified glue) that grouped by key}
console.log(groupConcatArr2d(testArr2d, {glue: "|glue|"}));
// get object: {value: concat key string with "|glue|"(specified glue) that grouped by value}
console.log(groupConcatArr2d(testArr2d, {swap: true, glue: "|glue|"}));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment