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));
Output:
Second Largest Element: 78
*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));
Output:
Sorted Array: [ 0, 0, 1, 2, 2, 3, 3, 4, 6, 8, 9, 78, 455 ]
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));
Output:
Unique Array of Element: [ 2, 3, 4, 6, 78, 0, 1, 455, 8, 9 ]
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));
Output:
Reverse Array of Elements: [ 9, 8, 455, 3, 2, 0, 1, 0, 78, 6, 4, 3 ]
I hope this is useful to you. Have a great day!
The above is the detailed content of Javascript Interview Coding Questions. For more information, please follow other related articles on the PHP Chinese website!