Site icon Tutorials Website: Upgrade Your Web Development & Coding Skills

Find the second largest element in an array using React

Find the second largest element in an array using React

Write a function to find the second largest element in an array. The function takes an array of integers given a string as an argument and returns the second max value from the input array. If there is no second max return -1.

Also Read: PHP Array Function

Let’s take some examples:

1. For array ["3", "-2"] should return "-2"

2. For array ["5", "5", "4", "2"] should return "4"

3. For array ["4", "4", "4"] should return "-1" (duplicates are not considered as the second max)

4. For [] (empty array) should return "-1".


Find the second largest element in an array

Simple Solution

The idea is to sort the array in descending order and then return the second element which is not equal to the largest element from the sorted array. Array value will be entered from the user using the input text.

import React, {useState} from "react";
//import logo from './logo.svg';
import './App.css';

function App() {

  let [result, setResult] = useState('');
  let [arr, setArr] = useState([]);

  const title="Find the second largest element";

 function saveInput(input) {
    let newArr=[...arr];
    let length=newArr.length;
  console.log(length+' : '+newArr);
   newArr[length]=input;
    setArr(newArr);
    console.log(length+' : '+newArr);
 
  };

function findSecondLagestNumber(arr=[]){

  arr = arr.sort((a, b) => (parseInt(b) - parseInt(a)));
  
  if(arr.length){

  let arr_size= arr.length / arr[0].length;
  setResult(print2largest(arr, arr_size));
  }else{
    setResult("-1");
  }

  function  print2largest(arr, arr_size){
    let i='';
    let array_size=arr_size;
    /* There should be atleast two elements */
    if (array_size <= 2) {
  
      array_size = array_size + 2;
    }
    
    console.log(array_size);
    for (i = array_size-2 ; i >= 0; i--) {
        // if the element is not
        // equal to largest element
        if (arr[i] !== arr[array_size - 1]) {
           console.log(arr[i])
            return arr[i];
        }
    }
  
    return "-1";
  }
}
function refreshPage() {
  window.location.reload(false);
}

  return (
    
{title}

Total Input Value :{arr}

{result}

saveInput(e.target.value)} />
Click outside the input box to store input value in array



); } export default App;

Input array value: array [“5”, “5”, “4”, “2”]

Output:

The second largest element is 4.

Complexity Analysis:

Also Read: How to convert array data into Simple XML file using PHP

Conclusion

Thank you for reading Find the second largest element in an array using React article. Hope I was able to help someone out. If you have any questions feel free to ask anything using the contact form. Cheers!!.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Exit mobile version