Skip to content

Instantly share code, notes, and snippets.

@shaunjacobsen
Created June 11, 2017 20:13
Show Gist options
  • Save shaunjacobsen/3b2cbd78429c119f10eb4ec9777dc777 to your computer and use it in GitHub Desktop.
Save shaunjacobsen/3b2cbd78429c119f10eb4ec9777dc777 to your computer and use it in GitHub Desktop.
function flatten(arr) {
var flattenedArr = [];
arr.forEach(function(nestedArr) {
// if the array has nested elements, proceed
if (nestedArr.length > 0) {
nestedArr.forEach(function(elem) {
// check if elem is already present in flattenedArr
if (!testNumberAndNumberAsString(elem, flattenedArr)) {
// if not, push it to the flattened array
flattenedArr.push(elem);
}
});
// if there are no nested elements, then return the input array
} else {
flattenedArr = arr;
}
});
return flattenedArr;
}
function testNumberAndNumberAsString(input, arr) {
var str = String(input);
var num = Number(input);
return (arr.includes(str) || arr.includes(num));
}
console.log(flatten([[1, '2', 3], [2, 3], [4, 5, 6], [5]]));
console.log(flatten([['a', 'b', 'c', 3], [3, 5]]));
console.log(flatten([]));
console.log(flatten([1]));
console.log(flatten([1, 2]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment