Q1. Reverse this string
let str = "Hello, World!";
let s = str.split("").reverse().join("");
console.log(s);
Q2. Remove duplicates
let arr = [1,2,3,4,5,6,6];
//let s = new Set();
let s = new Set(arr);
s.add(...arr);
for(let i =0;i<arr.length;i++){
s.add(arr[i]);
}
console.log(s);
Q3. Can you write a function in JavaScript to convert a string containing hyphens and underscores to camel case? transformation of the string โsecret_key_oneโ into camel case results in โsecretKeyOne.โ
let str = "secret_key_one";
let s = str.split("_");
console.log(s);
let ans = "";
for(let i = 0;i<s.length;i++){
if(i!=0){
ans+=s[i].substring(0, 1).toUpperCase();
ans+=s[i].substring(1);
}
else{
ans+=s[i];
}
}
console.log(ans);
Q4. Swap two numbers
let a =1, b=2;
Ans 1
a = a ^b;
b = a^b;
a = a^b;
console.log(a, b);
Ans 2
[a b] = [b.a];
Q5. Flatten this array
const arr = [1, 2, [3, 4]];
let ans = [];
const flatternArray = (arr) => {
for(let i =0;i<arr.length;i++){
if(Array.isArray(arr[i])){
flatternArray(arr[i]);
}else{
ans.push(arr[i]);
}
}
// console.log(ans);
};
flatternArray(arr);
console.log(ans);
Q6. const nestedObject = { a: { b: { c: 42 } } };
const propertyPath = 'a.b.c';
const result = deepAccess(nestedObject, propertyPath);
// result: 42
const nestedObject = { a: { b: { c: 42 }, z:{a:19} } };
const propertyPath = 'a.z.a';
// result: 42
let obj;
let arr = propertyPath.split('.');
// console.log(str);
const deepAccess = (nestedObject, arr) => {
if(arr.length==1){
// console.log("Reached end",nestedObject[arr[0]]);
return nestedObject[arr[0]];
}
let i = arr[0];
// console.log(i);
nestedObject = nestedObject[i];
arr.shift();
// console.log(arr);
return deepAccess(nestedObject, arr);
};
const result = deepAccess(nestedObject, arr);
console.log(result);
OR
let ans = arr.reduce((obj, ele) =>{
return obj[ele];
}, nestedObject);
console.log(ans);
Top comments (2)
let s = new Set();
let s = new Set(arr);
The symbol "s" has already been declared ;)
Oh Thanks,
I guess originally it was commented.
Anyways I've updated.