DEV Community

Aldi Kabulov
Aldi Kabulov

Posted on • Updated on

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

Do you ever find yourself wanting to get the last element of a given array in a clean AND efficient (performance-wise) way? Well, look no more, as this tutorial is right for you then.
Let's just over the required steps real quick:
Step 1. Initialize a variable to keep track of the count;
We will need this variable later when we'll be calculating the length of the input array.
Step 2. Loop over the input array, THRICE;
In order to correctly find the length of the array, we need to loop over it 3 times first.
Step 3. Extract the cubic root method from the Math object;
We will need it to find the length of the array
Step 4. Find the length of the array;
Using the aforementioned Math.cbrt() method, we will now find the length of the array
Step 5. Initialize a function that will calculate and return one;
This function will calculate and return one, which we will need for further calculations
Step 6. Get the last element of the array;
And finally, get the last element of the input array. Phew, finally!

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

console.log(getLastElementOfTheGivenArray([1, 2, 3, 4])); // expected output: 4
Enter fullscreen mode Exit fullscreen mode

If you enjoyed this JavaScript guide, make sure to stay tuned for future tutorials by me. Cheers!

Oldest comments (25)

Collapse
 
devlopr profile image
Aditya Mishra

How is array[-1] not faster than this?

Collapse
 
devfranpr profile image
DevFranPR

This obiously must be a joke post, look at the numbers.

Collapse
 
devlopr profile image
Aditya Mishra

Lol took me a while to understand 😹

Thread Thread
 
devfranpr profile image
DevFranPR

Blaze it!

Collapse
 
gentritbiba profile image
Gentrit Biba

That does not exist in javascript

Collapse
 
naziiriah profile image
`Nazir Abubakar

or array[array.length - 1]

Collapse
 
devlopr profile image
Aditya Mishra

Lol 😂😂 i forgot that array[-1] doesn't work, this answer of yours was what I meant but forgot to write the correct syntax

Collapse
 
djamaile profile image
Djamaile

You can use .at(-1) these days.

Collapse
 
ironcladdev profile image
Conner Ow

Epicly terrible and absolutely inefficient way. Please tell me you're joking.

Collapse
 
reservecrate profile image
Aldi Kabulov

No, I am completely serious.

Collapse
 
ironcladdev profile image
Conner Ow

For...of loops are proven to perform way slower than for(var i = 0; i < x; i++) normal for loops and for you to perform that operation thrice, it's gonna slow down your code dramatically.

Okay forget it, I literally am just not gonna talk to an absolute imbecile here. You wanna do it this way, then do it.

Collapse
 
kvetoslavnovak profile image
kvetoslavnovak

“ … += 1 - 1 + 1 - 2 + 5 - 3 …”
LOL 😂

Collapse
 
jonrandy profile image
Jon Randy 🎖️

I think you should set this up as a web service

Collapse
 
fjones profile image
FJones

Needs a graphql API, too, with a jwt authentication service.

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

Collapse
 
mistval profile image
Randall

It looks good but I think you can replace const one = 69 * 420 - 69 * 419 - 34 * 2; with const one = 2 - 1; maybe. A little bit more concise.

Collapse
 
bairavand profile image
Bairavan D

const arr = [1, 2, 3, 4]
console.log(arr[arr.length - 1])

Collapse
 
dedego profile image
Dennis de Goede

What about [1,2,3,4,5,6,7].slice(-1) // 7?

Collapse
 
pengeszikra profile image
Peter Vivo

no that result is one element array : [7]

[1,2,3,4,5,6,7].slice(-1)?.[0];
Enter fullscreen mode Exit fullscreen mode
Collapse
 
grahamthedev profile image
GrahamTheDev

While this is very funny please remove the beginners and tutorial tags, a new developer may not get the joke and think that this is indeed a fast way to find the last item in an array.

Collapse
 
devfranpr profile image
DevFranPR

This

Collapse
 
mradbourne profile image
Matt Radbourne

Lol! "THRICE"

Collapse
 
urielsouza29 profile image
Uriel dos Santos Souza

array[array.length-1]

arr.at(-1)

Collapse
 
codingjlu profile image
codingjlu • Edited

I think this is a better way (it took me a lot of work):

function lastElement(arr) {
  switch (arr.length) {
    case 1:
      return arr[0];
    case 2:
      return arr[1];
    case 3:
      return arr[2];
    case 4:
      return arr[3];
    case 5:
      return arr[4];
    case 6:
      return arr[5];
    case 7:
      return arr[6];
    case 8:
      return arr[7];
    case 9:
      return arr[8];
    case 10:
      return arr[9];
    case 11:
      return arr[10];
    case 12:
      return arr[11];
    case 13:
      return arr[12];
    case 14:
      return arr[13];
    case 15:
      return arr[14];
    case 16:
      return arr[15];
    case 17:
      return arr[16];
    case 18:
      return arr[17];
    case 19:
      return arr[18];
    case 20:
      return arr[19];
    case 21:
      return arr[20];
    case 22:
      return arr[21];
    case 23:
      return arr[22];
    case 24:
      return arr[23];
    case 25:
      return arr[24];
    case 26:
      return arr[25];
    case 27:
      return arr[26];
    case 28:
      return arr[27];
    case 29:
      return arr[28];
    case 30:
      return arr[29];
    case 31:
      return arr[30];
    case 32:
      return arr[31];
    case 33:
      return arr[32];
    case 34:
      return arr[33];
    case 35:
      return arr[34];
    case 36:
      return arr[35];
    case 37:
      return arr[36];
    case 38:
      return arr[37];
    case 39:
      return arr[38];
    case 40:
      return arr[39];
    case 41:
      return arr[40];
    case 42:
      return arr[41];
    case 43:
      return arr[42];
    case 44:
      return arr[43];
    case 45:
      return arr[44];
    case 46:
      return arr[45];
    case 47:
      return arr[46];
    case 48:
      return arr[47];
    case 49:
      return arr[48];
    case 50:
      return arr[49];
    case 51:
      return arr[50];
    case 52:
      return arr[51];
    case 53:
      return arr[52];
    case 54:
      return arr[53];
    case 55:
      return arr[54];
    case 56:
      return arr[55];
    case 57:
      return arr[56];
    case 58:
      return arr[57];
    case 59:
      return arr[58];
    case 60:
      return arr[59];
    case 61:
      return arr[60];
    case 62:
      return arr[61];
    case 63:
      return arr[62];
    case 64:
      return arr[63];
    case 65:
      return arr[64];
    case 66:
      return arr[65];
    case 67:
      return arr[66];
    case 68:
      return arr[67];
    case 69:
      return arr[68];
    case 70:
      return arr[69];
    case 71:
      return arr[70];
    case 72:
      return arr[71];
    case 73:
      return arr[72];
    case 74:
      return arr[73];
    case 75:
      return arr[74];
    case 76:
      return arr[75];
    case 77:
      return arr[76];
    case 78:
      return arr[77];
    case 79:
      return arr[78];
    case 80:
      return arr[79];
    case 81:
      return arr[80];
    case 82:
      return arr[81];
    case 83:
      return arr[82];
    case 84:
      return arr[83];
    case 85:
      return arr[84];
    case 86:
      return arr[85];
    case 87:
      return arr[86];
    case 88:
      return arr[87];
    case 89:
      return arr[88];
    case 90:
      return arr[89];
    case 91:
      return arr[90];
    case 92:
      return arr[91];
    case 93:
      return arr[92];
    case 94:
      return arr[93];
    case 95:
      return arr[94];
    case 96:
      return arr[95];
    case 97:
      return arr[96];
    case 98:
      return arr[97];
    case 99:
      return arr[98];
    case 100:
      return arr[99];
    default:
      return arr[arr.length - 1]; // fallback for less efficient way
  }
}
Enter fullscreen mode Exit fullscreen mode

If anyone likes it you can request me for some more. All that hard work 😅

And of course, the less efficient but nice one-liner:

const lastElem = arr => arr[Math.abs(~arr.lastIndexOf(arr[arr.length - 1])) - 1];
Enter fullscreen mode Exit fullscreen mode