I need a function that can search through an array of objects to find the last object where a specific value matches the one stored in the object.
Instead of returning all matching objects or just the first one, I am looking to return only the very last object where the specified name matches name = array[i].name
.
var allInfo = [
{name: "Olaf", lastname: "Kranz", age:33},
{name: "Mark", lastname: "Alien", age:21},
{name: "Cindy", lastname: "Sunsi", age:65},
{name: "Anna", lastname: "Pitter", age:20},
{name: "Piet", lastname: "Schmitz", age:29}
];
var name = 'Cindy';
document.write(getIfNameIsAvailable(name));
function getIfNameIsAvailable(name) {
for (i = allInfo.length; i >= 0; i--) {
if (allInfo[i].name == name) {
return allInfo[i].lastname;
break;
}
}
};