DEV Community

FatimaAlam1234
FatimaAlam1234

Posted on • Updated on

JavaScript Coding Interview Questions

Q1. Reverse this string

let str = "Hello, World!";
let s = str.split("").reverse().join("");
console.log(s);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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];
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

OR

let ans = arr.reduce((obj, ele) =>{
  return obj[ele];
}, nestedObject);

console.log(ans);
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
la_tiuscia profile image
la_tiuscia

let s = new Set();
let s = new Set(arr);

The symbol "s" has already been declared ;)

Collapse
 
fatimaalam1234 profile image
FatimaAlam1234

Oh Thanks,
I guess originally it was commented.
Anyways I've updated.