DEV Community

Cover image for Javascript Interview Coding Questions
Neetu J
Neetu J

Posted on • Edited on

Javascript Interview Coding Questions

1. Write the code for the second largest element in an Array.

Code:

const arr=[2,3,4,6,78,0,1,0,2,3,455,8,9];

   function secondLargest(arr){
      const sortedArray=[...new Set(arr)].sort((a,b)=>b-a);

      return sortedArray.length>=2 ? sortedArray[1] : null;
   }

  console.log("Second Largest Element:",secondLargest(arr));

Enter fullscreen mode Exit fullscreen mode

Output:

Second Largest Element: 78
Enter fullscreen mode Exit fullscreen mode

2. Write the code to Sort the array without using the built-in
function.

Code:

const arr=[2,3,4,6,78,0,1,0,2,3,455,8,9];

   function sortArray(arr){
      let temp=0;

     for(let i=0;i<arr.length;i++){
         for(let j=arr.length-1;j>i;j--){
             if(arr[i]>arr[j]){
                temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
               }
          }
      }
      return arr;
   }
   console.log("Sorted Array:",sortArray(arr));
Enter fullscreen mode Exit fullscreen mode

Output:

Sorted Array: [
    0, 0, 1, 2, 2,  3,
    3, 4, 6, 8, 9, 78,
    455
   ]
Enter fullscreen mode Exit fullscreen mode

3. Find out the unique element in an array without using 'Set'.

Code:

const arr=[2,3,4,6,78,0,1,0,2,3,455,8,9];

   function uniqueArray(arr){
      let tempArray=[];
      for(let i=0;i<arr.length;i++){
          if(tempArray.indexOf(arr[i])===-1){
            tempArray.push(arr[i]);
          }
       }
       return tempArray;
   }
   console.log("Unique Array of Element:",uniqueArray(arr));
Enter fullscreen mode Exit fullscreen mode

Output:

Unique Array of Element: [
     2, 3,   4, 6, 78,
     0, 1, 455, 8,  9
     ]
Enter fullscreen mode Exit fullscreen mode

4. Write the code for reverse the array without using built-in
function.

Code:

const arr=[2,3,4,6,78,0,1,0,2,3,455,8,9];

      function reverseArray(arr){
         let tempArray=[];
         for(let i=arr.length-1;i>0;i--){
            tempArray.push(arr[i]);
         }
       return tempArray;
      }
      console.log("Reverse Array of Elements:",reverseArray(arr));
Enter fullscreen mode Exit fullscreen mode

Output:

 Reverse Array of Elements: [
     9, 8, 455,  3, 2,
     0, 1,   0, 78, 6,
     4, 3
     ]
Enter fullscreen mode Exit fullscreen mode

I hope this is useful to you. Have a great day!

Top comments (0)