Skip to content

Instantly share code, notes, and snippets.

@arosca
Last active January 5, 2020 08:47
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 arosca/69184e43c319f84f09d2815a78956807 to your computer and use it in GitHub Desktop.
Save arosca/69184e43c319f84f09d2815a78956807 to your computer and use it in GitHub Desktop.
Flatten an array of nested arrays of integers
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