How to find previous data in every rows()every function

How to find previous data in every rows()every function

spiderkznspiderkzn Posts: 48Questions: 14Answers: 0
edited March 26 in Free community support

Hi,

I'm still struggle to find information. So it might be complicate. as I have no problem with read every rows with validation. So What I need to find information from previous row.

For eg:

Name Age
AB 13
CD 15
EF 56
GH 44
IJ 77

When the function read on EF. But I would like get the previous row name from CD. Would it possible?

My code here is

$("#person-history")
.DataTable()
.rows()
.every(function () {
let info = this.data();
console.log(info["Name"] + " " + info["Age"] + " " + "Previously: " + --- need put previous Row of name --- );
});

Answers

  • spiderkznspiderkzn Posts: 48Questions: 14Answers: 0

    The answer should be:

    AB 13 Previously:
    CD 13 Previously: AB
    EF 13 Previously: CD
    GH 13 Previously: EF
    IJ 13 Previously: GH

  • kthorngrenkthorngren Posts: 21,838Questions: 26Answers: 5,048

    You should be able to use a Javascript variable for this. Something like this:

    let previous = "";
    
    $("#person-history")
        .DataTable()
        .rows()
        .every(function () {
            let info = this.data();
            console.log(info["Name"] +  "   "  + info["Age"] + " " + "Previously: " + previous );
    
            previous = info["Name"] ;
        });
    

    Kevin

  • allanallan Posts: 64,216Questions: 1Answers: 10,598 Site admin

    Rows are considered to be independent from each other in DataTables. This is required for ordering. For example, is the "previous row" the one prior to the current row, for the currently applied sorting, or is it by data index? What happens if the end user changes the sorting? What about filtering?

    What I'd suggest doing is reading the data in an array:

    table.rows().data().toArray();
    

    and then iterate over that with a simple for loop, and you can easily get the previous step.

    That will do the logging you have above, in the most efficient way, but I'm not sure if that is what you eventual goal is?

    Allan

Sign In or Register to comment.