0

I'm trying to get the only last visited page by the user, it should update on every page. I tried to save the URL in session cookie from there I'm retrieving the last visited page.

This is my code:

function getSecondCookie(cSname) {
    var name = cSname + "=";
    var ca = document.cookie.split(';');
    for ( var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0)
            return c.substring(name.length, c.length);
    }
    return "";
}

function checkHistory(targetId) {
    var history = getSecondCookie("history");
    var htmlContent = '';

    if (history != "") {
        var insert = true;
        var sp = history.toString().split(",");
        for ( var i = sp.length - 1; i >= 0; i--) {
            htmlContent += '<a class="previous_url"  href="'
                    + sp[i]
                    + '">'
                    + sp[i].substring(sp[i].lastIndexOf('/') + 1) + '</a><br>';
            if (sp[i] == document.URL) {
                insert = false;
            }
            document.getElementById(targetId).innerHTML = htmlContent;
            console.log(sp[i]);
        }
        if (insert) {
            sp.push(document.URL);
        }
        setSecondCookie("history", sp.toString(), 30);
    } else {
        var stack = new Array();
        stack.push(document.URL);
        setSecondCookie("history", stack.toString(), 30);
    }
}

This is working fine how it has to. At the moment it is showing like this:

https://www.example.com,https://www.example.com/about.html

and so on.

But I want here show only last element from an array. How can I do this?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Zain
  • 662
  • 9
  • 26
  • Why do your cookie functions have "Second" inthe names? They just set and get the cookie you specify, there's no order to them. – Barmar Jun 11 '19 at 10:27
  • Possible duplicate of [Reference last element of an array in Javascript?](https://stackoverflow.com/questions/15672990/reference-last-element-of-an-array-in-javascript) – Mosè Raguzzini Jun 11 '19 at 10:31
  • Possible duplicate of [Get the last item in an array](https://stackoverflow.com/questions/3216013/get-the-last-item-in-an-array) – VLAZ Jun 11 '19 at 10:59

2 Answers2

6
let lastItem = array[array.length-1];
Cuttsy27
  • 81
  • 1
  • 7
0

You can also do:

const last = array.slice(-1)[0]
Umair Sarfraz
  • 5,284
  • 4
  • 22
  • 38