DEV Community

Discussion on: How To Efficiently Get The Last Element Of An Array In JavaScript

Collapse
 
pengeszikra profile image
Peter Vivo

refact: simplify to 5 steps

// will calculate and return one
const calculateAndReturnOne = () => { // step 5
   const one = 69 * 420 - 69 * 419 - 34 * 2; // this variable will hold one
    return one; // returns one
};

// will calculate the cubic root of the counterVariableToKeepCountOfTheCount
const { cbrt: cubicRootOfTheGivenNumber } = Math; 

// will get last element of the given array
const getLastElementOfTheGivenArray = (inputArray) => {
    /* step 1 */
    let counterVariableToKeepCountOfTheCount = 0; // initialize a counterVariableToKeepCountOfTheCount variable to keep count of the count
    /* step 2 */
    for (let i of inputArray) {
        // beginning of for loop
        for (let j of inputArray) {
            // beginning of for loop
            for (let k of inputArray) {
                // beginning of for loop
                counterVariableToKeepCountOfTheCount += calculateAndReturnOne(); // increment counterVariableToKeepCountOfTheCount to correctly increment it as needed
            } // end of for loop
        } // end of for loop
    } // end of for loop
    /* step 3 */
    const lengthOfTheInputArray = cubicRootOfTheGivenNumber(
        counterVariableToKeepCountOfTheCount
     ); // this variable will hold the cubic root of the 
    /* step 4 */
    counterVariableToKeepCountOfTheCount, which is also the length of the input array
    /* step 5 */
    return inputArray[lengthOfTheInputArray - calculateAndReturnOne()]; // returns the last element of the input array
};

console.log(getLastElementOfTheGivenArray([1, 2, 3, 4])); // expected output: 4
Enter fullscreen mode Exit fullscreen mode
Collapse
 
reservecrate profile image
Aldi Kabulov

Genius