Skip to content

Instantly share code, notes, and snippets.

@leodevbro
Last active October 8, 2021 19:32
Show Gist options
  • Save leodevbro/7c6e3ab1ea062ac8d73c403fa61c3115 to your computer and use it in GitHub Desktop.
Save leodevbro/7c6e3ab1ea062ac8d73c403fa61c3115 to your computer and use it in GitHub Desktop.
// 1)
console.log(3, typeof 3); // 3 "number"
console.log("a", typeof "a"); // "a" "string"
console.log(2, typeof 2, "a", typeof "a"); // 2 "number" "a" "string"
// 2) Recursion
const getUniqueSortedNumbers = (root) => {
const mySet = new Set();
function traverse(x) {
if (Array.isArray(x)) {
traverseArray(x);
} else if (typeof x === "object" && x !== null) {
traverseObject(x);
} else {
if (typeof x === "number") {
mySet.add(x);
}
}
}
function traverseArray(arr) {
arr.forEach(function (x) {
traverse(x);
});
}
function traverseObject(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
traverse(obj[key]);
}
}
}
traverse(root);
return([...mySet].sort((a, b) => a - b));
};
// usage:
const testObject001 = {
a: {
x: 3,
y: {
d: 2,
e: 2,
f: {
g: 4,
},
z: 8,
},
},
};
const result = getUniqueSortedNumbers(testObject001); // [2, 3, 4, 8];
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment