Home > OS >  How to find latest or last element value from array object using jQuery
How to find latest or last element value from array object using jQuery

Time:10-01

How to find latest/last element value from the array object based on condition using jQuery. Each array object contains multiple items. Like Array(0) object contains multiple item with value, Array(1) also contains multiple item with value.....Array(2)...etc.

For example-

Array(0) object has items Name:Ravi ,VisitingDate:20/07/2021.
Array(1) object has items Name:Ravi ,VisitingDate:15/08/2021.
Array(2) object has items Name:Ravi ,VisitingDate:30/09/2021 . 

    

I want to return latest or last visitingDate value as 30/09/2021 whose name is Ravi using JQuery.

I have tried below JQuery. But it always return first element from array for VisitingDate value as 20/07/2021 which is wrong. It should return last/latest element(VisitingDate) value from array.

if (arryObj.find((o) => { return o["Name"] === "Ravi" }) !== undefined)
 {                        
var VisitDate = arryObj.find((o) => { return  o["Name"] === "Ravi" }).VisitingDate
}

CodePudding user response:

Use filter:

    let array = [];
        array.push({
            'Name':'Ravi',
            'VisitingDate': '20 / 07 / 2021',
        });
        array.push({
            'Name': 'Ravi',
            'VisitingDate': '20 / 07 / 2021',
        });
        array.push({
            'Name': 'Ravi',
            'VisitingDate': '12 / 09 / 2021',
        });
    let last_element = array.filter(function (ar) { return ar.Name == 'Ravi' }).at(-1);
    console.log(last_element);
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

  • Related