Retrieve the name of the current item at the end of the list

Is there a way to retrieve the last item on the list marked as success?

children: [
   {
    case: "no-success",
    name: "bruno",
    endOffset: 5
   },
   {
    case: "no-success",
    name: "pippo",
    endOffset: 5
   }
   {
    case: "success",
    name: "jo",
    endOffset: 5
   },
   {
    case: "success",
    name: "Matteo",
    endOffset: 5
   },
   {
    case: "np-success",
    name: "Robert",
    endOffset: 5
   }
]

I am specifically looking for the item with the name Matteo.

To find the first matching item, I use: var foundIdx = this.newListWords[i].children.find(item => item.case === 'success').

Answer №1

Explanation:

The find() function locates and retrieves the FIRST element in a given array that meets the specified condition. If no elements meet the criteria, undefined is returned.

To reverse an array:

this.newListWords[i].children.reverse().find(item => item.case === 'success')

Alternatively, you can use filter to extract the last child:

const filtered = this.newListWords[i].children.filter(item => item.case === 'success')
const lastFind = filtered[filtered.length-1]

Answer №2

function findLastSuccessValue(list: any[]): any {
  const SUCCESS = 'success';
  const [lastElement] = list // Get the first element of the list
    .filter(obj => obj.success === SUCCESS) // Look for successful items
    .reverse(); // Reverse the list
  return lastElement;
}
const result = findLastSuccessValue(this.newListWords[i].children);

Answer №3

    var kids = [
       {
        type: "fail",
        label: "bruno",
        offset: 5
       },
       {
        type: "fail",
        label: "pippo",
        offset: 5
       },
       {
        type: "pass",
        label: "jo",
        offset: 5
       },
       {
        type: "pass",
        label: "Matteo",
        offset: 5
       },
       {
        type: "partial",
        label: "Robert",
        offset: 5
       }
    ];
    
    function getLastPass(kids) {
        if (!Array.isArray(kids)) {
            return {};
        }
        for (var j = kids.length - 1, obj; obj = kids[j]; j--) {
            if (obj.type === 'pass') {
                return obj;
            }
        }
    }
    
    console.log(getLastPass(kids));

Answer №4

A simple line of code

const result = children.reduce((s, c) => { if (c.case === "success") { return c }  else { return s } }, null);

If no success is found, the result will be null.

Answer №5

Using this code will retrieve the final element within the sorted list that contains 'success',

children.findLast(item => item.case === 'success')

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

The button fails to trigger the AJAX request

I've developed a form that includes a QR code generator. The QR code is generated as an SVG, and below the code is a download button that should trigger an AJAX call to my PHP script when clicked. However, the download button does not seem to initiate ...

Could someone teach me how to implement icon rotation in Vue.js using Vuetify?

I am currently working on adding a feature where the icon rotates when the button is clicked, moving from down to up and vice versa in a spinning motion. Here is the code I have so far: <template> <v-btn v-on:click="isShow = !isShow" ...

Encountered a snag while executing Powershell with Selenium: Error message - unable to interact with

Looking to update a textarea with a value? The script below triggers an error stating "element not interactable". This occurs because the textarea is set to "display:none". However, manually removing the "NONE" word allows the script to successfully set th ...

Issue encountered while using Typescript with mocha: Unable to utilize import statement outside a module

Exploring the world of unit testing with mocha and trying to create a basic test. Project Structure node_modules package.json package-lock.json testA.ts testA.spec.ts tsconfig.json tsconfig.json { "compilerOptions": { "target&qu ...

Adding pointlights to the camera in three.js is a great way to

I have written some code to add two lights on the camera that move along with the orbitcontrols. However, the lights and spheres are not visible for some reason. Can someone help me identify the issue in my code? var sphere1 = new THREE.Mesh( new THREE.Sp ...

Experiencing difficulty connecting to WebSocket while running the app on Heroku (Node.js) platform

After attempting to deploy my web application utilizing Websockets on Heroku, I found that I am unable to connect to the designated listening port. //Server const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8000 }); app.u ...

React Component: Issue with conditional "if else" statement not refreshing in return statement

Starting out in React and the front-end field with minimal experience. Currently attempting to dynamically change the color of the "fill" property in a polygon element using React. If the percentage is greater than 50, I want the color to be green; otherw ...

Struggling with a 400 Bad Request Error in Angular with WebAPI Integration

I've been working on creating a database to keep track of comics, and so far I can successfully add new comics and retrieve them using GET requests. However, I've hit a roadblock when trying to update existing comics using PUT requests. Every tim ...

Transforming a text file into an array using fs in Node.js

My text file contains the following: {"date":"2013/06/26","statement":"insert","nombre":1} {"date":"2013/06/26","statement":"insert","nombre":1} {"date":"2013/06/26","statement":"select","nombre":4} Is there a way to convert the text file contents ...

Is there a way to access the value of a variable that is defined in FileReader.onloadend from within the callback function of XMLHttpRequest.onreadystatechange

I'm trying to access the value of the variable ext (defined within the function reader.onloadend) in the function xhr.onreadystatechange. Currently, it is returning undefined. Does anyone have any suggestions on how to resolve this issue? function pr ...

Enhance the user experience by incorporating a tooltip into the input field using Bootstrap 5

I have implemented custom CSS to display an error icon with a tooltip, but after upgrading to Bootstrap 5, I am unable to achieve the same result. Expected: https://i.sstatic.net/Mjvik.png .icon { position: absolute; bottom: 6px; right: 10.5px; ...

Is it necessary to incorporate express in a Next.js project?

I'm currently working on a website using Next.js. With Next.js, I have access to features like SSR and dynamic routing. Is it necessary for me to incorporate express into my project? If yes, what are the reasons behind needing to use it? What unique ...

Having issues with importing momentjs by reference in TypeScript with amd configuration

I'm puzzled by the difference in behavior between these two snippets: import * as moment from "../Typings/moment"; One works, while this one doesn't: /// <reference path="../Typings/moment.d.ts" /> import * as moment from "moment"; It t ...

Issue encountered: The Android build is failing with the error message stating that "null is not

I recently integrated a private gitlab repo (react native module) into my App's package.json. The index file within my private gitlab repo can be viewed here: https://i.sstatic.net/uObHe.png For iOS methods, please refer to this link: https://i.ssta ...

The fetch method in Express.js resulted in an error 404 because the requested URL could not be found

Having trouble locating the URL when trying to fetch data for a POST request. I want to mention that my code is written in node.js and express.js. The error message being generated: const form = document.querySelector('form'); form.addEventList ...

The passport.use method is failing to invoke in Node.js when utilizing the passport-local strategy

Upon calling the login and submitting the form, it seems that the use.authenticate() method is not being executed and no error messages are displayed. Server.js code snippet: const passport=require('passport'); const Strategy=require('pass ...

Angular does not seem to be identifying the project name as a valid property

After installing Angular materials using the CLI, I decided to check my angular.json file and encountered an error in the console stating that "Property MEAN-APP is not allowed". [The name of my Angular project is MEAN-APP] Here's a screenshot of the ...

Is there a way to duplicate a GLTF model that has been imported into the Autodesk Viewer?

I encountered an issue while trying to dynamically clone a loaded GLB model and allow the user to position it in the scene. Despite using the model.clone() method, the cloned model ends up appearing at the same position as the original, causing changes in ...

Submit the form without displaying any output in the browser, not even in the view source code

I have a basic form that needs to be submitted multiple times, but I want the submission process to be hidden from the browser. Simply using "hidden" or "display:none" won't completely hide the form code when viewing the page source. I tried using PHP ...

What methods can be utilized to retrieve multiple objects based on their names?

It appears that it's not necessary for objects in the scene to have unique names; multiple objects can share the same name... If I need a list of these objects, do I need to create a getObjectsByName method or is there an alternative way to achieve t ...