Interview Questions- Part-4

Guess the output

				
					let question = () => {
  return
  {
    name: "anurag";
  }
};

console.log(question());

output:-undefined
				
			
				
					let question = () => {
  return {
    name: "anurag"
  };
};

console.log(question());

output:-
{name: 'anurag'}
				
			

Max and Min Sum

				
					//for 1 --> skip 1 -->Add other elements -->2+5+8+3=18
//for 2 --> skip 2 -->Add other elements -->1+5+8+3=17
//for 5 --> skip 5 -->Add other elements -->1+2+8+3=14
//for 8 --> skip 8 -->Add other elements -->1+2+5+3=11
//for 3 --> skip 3 -->Add other elements -->1+2+5+8=16
//Output Needed is as below
//Maximum Sum:-  18
//Mininum Sum:-  11
const number = [1, 2, 5, 8, 3];
const [minSum, maxSum] = [Math.min(...number), Math.max(...number)];
const finalSum = number.reduce((acc, curr) => acc + curr);
console.log("Maximum Sum:-", finalSum - minSum);
console.log("Mininum Sum:-", finalSum - maxSum);

				
			

Chunked Array

				
					//CHUNKED ARRAY
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
//n=3
//output should be
//[[1,2,3],[4,5,6],[7,8,9]]

//n=4
//output should be
//[[1,2,3,4],[5,6,7,8],[9]]

//n=7
//output should be
//[[1,2,3,4,5,6,7],[8,9]]

//n=10 or n=9
//[1,2,3,4,5,6,7,8,9]

let finalArray = [];
const chunkArray = (arr, n) => {
  if (n >= arr.length) {
    finalArray = arr;
    return arr;
  }
  while (arr.length !== 0) {
    let chunkedArray = arr.splice(0, n);
    finalArray.push(chunkedArray);
  }
};

chunkArray(arr, 9);
chunkArray(arr, 3);
chunkArray(arr, 4);
console.log(finalArray);
				
			

Check unique chatacters in a string

				
					let myName = "anurag";

//when it loops anurag..a is not there in final obj
//we get undefined...//!undefined is true
//we assign 1 finalObj['a'] =1

//next time when a comes in anurag ...
// finalObj['a'] is 1 goes to : part to increase the count
const isUnique = (str) => {
  const finalObj = {};
  for (let i of str) {
    !finalObj[i] ? (finalObj[i] = 1) : finalObj[i]++;
  }
  return finalObj;
};
let final = isUnique(myName);
//final::- {a: 2, n: 1, u: 1, r: 1, g: 1}
//to convert object to array
// We are converting values to array here

const finalArrayValues = Object.values(final);
//fianArrayValues=[2,1,1,1,1]
console.log(finalArrayValues.every((i) => i === 1));
				
			
				
					//2nd way
const isUnique = (str) => {
  let map = new Map();
  for (let i of str) {
    if (map.get(i)) {
      return console.log("name doesn't contain unique characters");
      //break;
    } else map.set(i, true);
  }
  console.log("name contains unique characters");
};

isUnique(myName);
				
			

Leave a Comment