Skip to content

Instantly share code, notes, and snippets.

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 pradhumnsharma/0b1a837ad1759a7c79dbf9db840c4279 to your computer and use it in GitHub Desktop.
Save pradhumnsharma/0b1a837ad1759a7c79dbf9db840c4279 to your computer and use it in GitHub Desktop.
Ques 1: Create a function named `customObjFlatten` which will take an pure nested object and return single level key value pair such as
INPUT
{
a: 12,
b: 15,
c: {
d: 31,
e: {
f:51,
g: {
h: 64,
i: 99
}
}
}
}
OUTPUT
{ a: 12, b: 15, c_d: 31, c_e_f: 51, c_e_g_h: 64, c_e_g_i: 99 }
SOLUTION
const blank = {};
function flatten(obj, prefix=""){
for(let key in obj){
let newKey = `${prefix}${key}`;
if(typeof(obj[key]) == 'object') {
return flatten(obj[key], `${newKey}_`)
} else {
blank[`${newKey}`] = obj[key]
}
}
console.log(blank)
}
flatten(obj1)
================================================================================================================================================================================================================================================================================
Ques 2: Create a function `customArrFlatten` which will take a nested array and create single level array such that:
INPUT
[1,2,3,[4,5,[6],[7], [8,9,10,[11]]]]
OUTPUT
[1,2,3,4,5,6,7,8,9,10,11]
SOLUTION
const flatArr = []
function customArrFlatten(arr){
for(let i = 0; i < arr.length; i++){
if(Array.isArray(arr[i])) {
return customArrFlatten(arr[i])
} else {
flatArr.push(arr[i])
}
}
}
customArrFlatten(arr)
==========================================================================================================================================
Ques 2: Find the pairs in an array having sum = n
INPUT
arr = [ 1, 8, 45, 6, 10, 8 ];
sum = 16
OUTPUT
(8.8), (10,6)
SOLUTION
let store = new Set();
let leng = arr.length;
for(let i = 0;i < leng;i++){
let temp = n - arr[i];
if(store.has(temp)){
console.log(`Pair: (${temp}, ${arr[i]})`);
}
store.add(arr[i])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment