Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Created July 23, 2019 11:25
Show Gist options
  • Select an option

  • Save anushshukla/489e8e00d69e16c444ecb5ad1cf16e98 to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/489e8e00d69e16c444ecb5ad1cf16e98 to your computer and use it in GitHub Desktop.
Flatten a nested array in sorted order
// Input
// [5, 10, 11, [2, 8], [12, 1, 4], [9, [5,4, 12]], 17]
// Output
// [1, 2, 4, 5, 8,9,10, 11, 12, 17]
function isArray(value) {
return value instanceof Array;
}
function getgetFlatArray2(arr) {
for (var i = 0; i < arr.length; i++) {
if (isArray(arr[i])) {
}
}
}
function getFlatArray(arr, index = 0, newArr = []) {
}
function getFlatArray(arr, index = 0, newArr = []) {
var currVal = arr[index];
if (isArray(currVal)) {
return getFlatArray(currVal);
}
newArr.push(currVal);
if (index === arr.length - 1) {
return newArr;
}
return getFlatArray(arr, index + 1, newArr);
}
function getSortedArray(arr, index = 0, newArr = []) {
var currVal = arr[index];
var prevVal = newArr[index - 1];
if (index) {
newArr.push(currVal);
} else if (currVal > prevVal) {
newArr.push(currVal);
} else {
for (var i = 0; i < newArr.length; i++) {
if (currVal > newArr[i]) {
newArr.splice(0, i, currVal);
break;
}
}
}
if (index === arr.length - 1) {
return newArr;
}
return getFlatArray(arr, index + 1, newArr);
}
function myfunction(arr) {
let outputArr = getSortedArray(getFlatArray(arr));
return outputArr;
}
var sampleArr1 = [5, 10, 11, [2, 8], [12, 1, 4], [9, [5,4, 12]], 17];
console.log(myfunction(sampleArr1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment