Last active
November 5, 2019 19:25
-
-
Save samcyn/1876d55ea000cb1f74ac9d1ff904b298 to your computer and use it in GitHub Desktop.
FLAT A LIST(ARRAY) USING JAVASCRIPT
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
/* | |
A - S I M P L E - F L A T - L I S T - H A N D L E R | |
- U S I N G - F L A T | |
*/ | |
const flatListHandler = (nestedArray, depth) => { | |
return nestedArray.flat(depth); | |
} | |
// U S A G E - | |
const nestedArray = [1, 2, 3 ,4 , [5, 6, 7], 8]; | |
const flattenList = flatListHandler(nestedArray, 1); | |
console.log(flattenList); // 1,2,3,4,5,6,7,8 | |
// NB DEPTH can be 1, 2, 3, 4 and so on | |
// if you want to go infinitely deep DEPTH can be set to Infinity | |
// Since not all browsers support this there are some couple of alternatives to use | |
// I've one written in another gist of mine couple of months ago | |
// https://gist.github.com/samcyn/4997504b6a41fb6d5ae201081f8d5fbc | |
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
// LET SAY YOU HAVE MOCHA AND CHAI SET UP | |
// A QUICK WAY TO TEST THIS UTILITY FUNCTION CAN BE AS FOLLOWS | |
import { assert } from 'chai'; | |
import flatListHandler from './solution'; | |
const nestedArray = [[1,2,[3]],4]; | |
describe('Basic Mocha String Test', function () { | |
it('should return flat list', function () { | |
assert.deepEqual(flatListHandler(nestedArray), [1,2,3,4]); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment