Last active
May 12, 2022 21:36
-
-
Save rauschma/76277fd5bfafc1e51fa2e72dac869723 to your computer and use it in GitHub Desktop.
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
//========== Solution 1: array.flatMap() and array.map() ========== | |
const prios = (arrayOfArrays) => arrayOfArrays.flatMap( | |
(arr, index) => { | |
return arr.map(elem => ({...elem, priority: index+1})) | |
} | |
); | |
// .flatMap() both maps and flattens | |
// More information: https://exploringjs.com/impatient-js/ch_arrays.html#Array.prototype.flatMap | |
assert.deepEqual( | |
prios([ | |
[ | |
{ name: 'Jane' }, | |
{ name: 'Tarzan' }, | |
], | |
[ | |
{ name: 'Cheeta' }, | |
], | |
]), | |
[ | |
{ name: 'Jane', priority: 1 }, | |
{ name: 'Tarzan', priority: 1 }, | |
{ name: 'Cheeta', priority: 2 }, | |
] | |
); | |
//========== Solution 2: nested for-of loops ========== | |
const prios2 = (arrayOfArrays) => { | |
const result = []; | |
for (const [index, arr] of arrayOfArrays.entries()) { | |
for (const elem of arr) { | |
result.push({...elem, priority: index+1}); | |
} | |
} | |
return result; | |
}; | |
assert.deepEqual( | |
prios2([ | |
[ | |
{ name: 'Jane' }, | |
{ name: 'Tarzan' }, | |
], | |
[ | |
{ name: 'Cheeta' }, | |
], | |
]), | |
[ | |
{ name: 'Jane', priority: 1 }, | |
{ name: 'Tarzan', priority: 1 }, | |
{ name: 'Cheeta', priority: 2 }, | |
] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment