Last active
January 5, 2020 08:47
-
-
Save arosca/69184e43c319f84f09d2815a78956807 to your computer and use it in GitHub Desktop.
Flatten an array of nested arrays of integers
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
const { expect } = require('chai'); | |
/** | |
* Flattens nested arrays | |
* @param {Array} array The array to flatten. | |
* @returns {Array} Returns the new flattened array. | |
*/ | |
const flatten = (arr: Array<any>): Array<number> => arr.toString().split(',').map(x => parseInt(x, 10)).filter(x => !!x) || []; | |
describe('flatten', () => { | |
it('should flatten nested arrays', () => { | |
const arr = [[1,2,[3]],4]; | |
const result = flatten(arr); | |
expect(result).to.have.members([1, 2, 3, 4]); | |
}); | |
it("ignores anything that's not a number", () => { | |
const arr = [1, 2, ['string', 3]]; | |
const result = flatten(arr); | |
expect(result).to.have.members([1, 2, 3]); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment