Skip to content

Instantly share code, notes, and snippets.

@hughsw
Last active May 25, 2019 13:45
Show Gist options
  • Save hughsw/93d855be057d17928759bbb532bea499 to your computer and use it in GitHub Desktop.
Save hughsw/93d855be057d17928759bbb532bea499 to your computer and use it in GitHub Desktop.
Javascript data wrangling
Real-world, little Javascript problem
Input is an array of strings.
Each string encodes a pair of 3-letter symbols, separated by an underscore '_'.
We talk about the left-hand and right-hand symbols that are encoded into the string.
E.g.
['AED_AFN', 'ALL_AMD', 'AMD_AFN', 'ALL_GBP']
'AED' is the left-hand symbol of the first pair; 'AFN' is the right-hand symbol of the first pair. Etc.
We want this data rearranged into an object.
This object organizes the symbols based on the left-hand symbol of each pair.
The keys in the object correspond to the left-hand, 3-letter symbols of the input array.
The value for each key is an array of the right-hand, 3-letter symbols from the pairs that have the key as their left-hand symbol.
E.g, given the above input, we want
{ AED: ['AFN'], ALL: ['AMD', 'GBP'], AMD: ['AFN'] }
Code template:
const collectSymbols = pairs => {
const collectedSymbols = {};
... code to populate collectedSymbols
return collectedSymbols;
};
So:
collectSymbols(['AED_AFN', 'ALL_AMD', 'AMD_AFN', 'ALL_GBP']);
returns:
{ AED: ['AFN'], ALL: ['AMD', 'GBP'], AMD: ['AFN'] }
Or:
console.log(JSON.stringify(collectSymbols(['AED_AFN', 'ALL_AMD', 'AMD_AFN', 'ALL_GBP']));
Emits:
{"AED":["AFN"],"ALL":["AMD","GBP"],"AMD":["AFN"]}
Think about breaking the problem into smaller pieces, or passes, that can be done separately.
Outline with a few bullet items, a couple of approaches.
Focus on simplicity of code rather than an optimized ideal.
It's generally much more important to get code working than to get code to be optimal according to some criteria
Hints:
- String split() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
- Array map() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
- Array forEach() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment