JavaScript function that returns the last object whose value matches a specified value

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;
    }
  }
};

Answer №1

There are three key issues to address:

  1. The correct array indexes range from length - 1 through 0, not starting from length. This is the reason why your code encounters an error during the first execution.
  2. It is unnecessary to use break after return since return already exits the function, including the loop.
  3. It is essential to declare all variables properly, including loop counters like i. Failure to do so may lead to what is known as The Horror of Implicit Globals.

Incorporating these corrections by adjusting for the - 1, removing break, and declaring i correctly— I also made a slight alteration by changing Mark Allen's name to Cindy in order to verify that it indeed fetches the last instance of Cindy:

var allInfo = [
  {name: "Olaf", lastname: "Kranz", age:33},
  {name: "Cindy", 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 (var i = allInfo.length - 1; i >= 0; i--) {
    if (allInfo[i].name == name) {
      return allInfo[i].lastname;
    }
  }
};

Answer №2

It has been pointed out by @T.J Crowder (Legend) why you encountered the issue. Here is an alternate approach that may help avoid such problems in the future. Consider utilizing JavaScript’s pre-built utilities like .find. This can simplify your code significantly with just one line.

allInfo.find(o=> o.name === 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) {
  return allInfo.find(o=> o.name === name).lastname
};

Answer №3

const peopleList = [
  {firstName: "Olaf", lastName: "Kranz", age:33},
  {firstName: "Mark", lastName: "Alien", age:21},
  {firstName: "Cindy", lastName: "Sunsi", age:65},
  {firstName: "Anna", lastName: "Pitter", age:20},
  {firstName: "Piet", lastName: "Schmitz", age:29},
  {firstName: "Cindy", lastName: "Surname", age: 22}
];

const checkIfNameExists = (name, array) => array.slice(0).reverse().find(item => item.firstName == name);

const personInfo = checkIfNameExists('Cindy', peopleList);

Answer №4

Exploring a while loop with an index decremented after each check.

function findLastNameByName(name) {
    var i = allInfo.length

    while (i--) {
        if (allInfo[i].name === name) {
            return allInfo[i].lastname;
        }
    }
}

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 }];

console.log(findLastNameByName('Cindy'));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am having trouble unzipping the file

I encountered an issue while attempting to download a .zip file from Discord and extracting it using the decompress package. Despite not returning any errors, the package did not get extracted as expected. (The file was saved and downloaded correctly) co ...

Typescript is a lifesaver when it comes to handling JSON arrays with optional properties. Its assistance is unparalleled

I am working with a typescript object that looks like this: class myObj { public param1, public param2, public param3 } In another object, I have an array of that same object class otherObj { public arrayOfMyObj:myObj[] constructor(){ ...

Using Java methods to add elements to a multidimensional array of users

Here's the scenario I'm dealing with: "I need to develop a program that can manage user input information such as First Name, Last Name, Phone Number, and Age. The challenge is to store this data in a multidimensional array with 10 contacts, whe ...

What is the process for showcasing a local notification within my application?

Here is the code snippet I am working with: import { LocalNotifications } from '@ionic-native/local-notifications'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scs ...

Guide to using Angular $resource to pass query parameter array

My goal is to implement a feature that allows users to be searched based on multiple tags (an array of tags) using the specified structure: GET '/tags/users?tag[]=test&tag[]=sample' I have managed to make this work on my node server and hav ...

React developer server is failing to automatically refresh the code

I've encountered an issue with react-dev-server where changes I make to the code do not reflect on the app itself even after refreshing (not hot-loading). I've tried setting up my own project as well as using Facebook's Create-react-app, whi ...

Explore vue3 components using vue-test-library and universal components

I started creating unit tests for a production app using jest, @testing-library/vue, and supporting libraries. The first test I created is as follows: import vue from "vue"; import { render } from "@testing-library/vue"; import LibBtn f ...

timings and pauses utilizing JavaScript

Currently, I am facing a challenge while working on a Simon Says game. My struggle lies in the part where I need to illuminate the buttons that the user has to click. I am using a "for" loop to iterate through each element in the array where I have stored ...

Angular Ionic: Unable to compare 'value'. Only arrays and iterable objects are permitted for differentiation

I attempted to display a list value and when I logged the value of the list, it appeared exactly how I wanted: unit value {id: 81, name: "3 BR Suite"} unit value {id: 82, name: "3 BR Grande"} unit value {id: 83, name: "Pool Villa&q ...

Exploring the functionalities of a personalized jQuery slider's next button

I created a container div with three inner divs, each having a class of "content" and one of them having a class of "current". My goal was to display only one ".content" at a time and have a "next" button that hides the current div, removes the "current" c ...

Execute a node script file at random intervals

I've been utilizing forever to maintain the continuous execution of a node script: forever start script1.js However, my requirement is to run these files in a random order... For instance: Execute node script1.js Execute node script2.js Run script ...

Guide on implementing the 'cut' feature using electron-localshortcut

Looking for a way to use keyboard shortcuts on Mac without relying on the menu? I recently came across this helpful post: Is it possible to create non-global accelerators without adding them to a menu? Thanks to this informative article, I learned about ...

Display the information in a Bootstrap modal fetched from a database by utilizing AJAX, PHP, and JavaScript

I've been struggling to display the description in a bootstrap modal. I can retrieve the price, quantity, list price, and title from the database without any issues, but as soon as I try to fetch the description data, all my information vanishes. I&ap ...

JavaScript issue: "Error: Uncaught (in promise) SyntaxError: Unexpected end of input"

Encountering the following error message: Uncaught (in promise) SyntaxError: Unexpected end of input when attempting to post references to my specific express server. Can anyone here offer assistance? function create() { event.preventDefault() fi ...

Leverage NodeJS data within Angular framework

I am working with the following route: Server app.get('/claim/:id', compact.js(['global']), indexController.claim); module.exports.claim=function(req,res){ res.render('claim-note', { title: 'claim', noteId:req. ...

Issue with Bottle.py: When using AJAX, request.forms.get() is returning NoneType

Having trouble sending JavaScript data to a bottle.py server using AJAX? Despite trying numerous solutions from various sources, none seem to be working. To provide clarity, I'm focusing on the AJAX call code here. Can someone explain why request.for ...

Tips for sending an array with all its elements from jQuery to PHP

Currently, I am attempting to transfer an array from jQuery to PHP. <input type="checkbox" id="name1" name="name[]" value="name1"> Name1 <input type="checkbox" id="name2" name="name[]" value="name2"> Name2 <input type="checkbox" id="name3" ...

What is the best way to transform a one-dimensional object array into a two-dimensional array in a Vue component, based on a specific key?

My vue modules are structured like this: [types.GET_PRODUCT_CATEGORIES] (state,{ stores }) { state.product_categories = {} console.log(stores); stores.forEach(message => { set(state.product_categories, message.id ...

npm encountered a premature closure

I recently purchased and started using a ReactJS template which you can check out here My goal is to install all the dependencies by running npm install in the root directory of the template (React-App) However, I encountered an ERROR message like this: ...

Ways to obtain the <a> using the title attribute

Is there a way to remove 3 classes from a specific <a> element that is dynamically generated? The only constant is the title. How can I locate an element based on its title? I've searched online but haven't found exactly what I'm looki ...