0

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
}

4
  • 1
    Welcome to SO. Please try to enter sample data and expected output too. It helps us. Kudos on adding your attempt. Commented Sep 30, 2021 at 19:08
  • Which part of your code specifies that the latest date should be returned? Commented Sep 30, 2021 at 19:15
  • I have entered example and my expected result in my question description. Commented Sep 30, 2021 at 19:18
  • Inside if condition there is a code which is having VisitingDate. This should return the latest VisitingDateas 30/09/2021 instead of first VisitingDate value as per my example in above .var VisitDate = arryObj.find((o) => { return o["Name"] === "Ravi" }).VisitingDate Commented Sep 30, 2021 at 19:21

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.