Locate and return the index in Typescript

Can you get the index of an element in an array using the array.find() method in TypeScript?

For example, I know I can use find to retrieve an object based on a property value, but is it possible to also retrieve the index of that object in the array?

Answer №1

To determine the index, you can utilize Array.findIndex

Here is an example:

const array1 = [5, 12, 8, 130, 44];

console.log(array1.findIndex((element) => element > 13));

To retrieve the actual value at that index:

const array1 = [5, 12, 8, 130, 44];

const idx = array1.findIndex((element) => element > 13);

console.log(array1[idx])

Answer №2

The responses above are accurate in stating that you can use .findIndex() to retrieve the index and .find() to get the actual entry from the array.

However, it appears that you are questioning how to obtain both the index and the entry simultaneously from the array.

If my assumption is correct, you may consider trying the following approach:

    let array  = ["Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"];
                
    let tuesday = array.map((day,index) => {
       if(day == "Tuesday")
         return {day, index}
    }).filter(day => day)[0];

    console.log(tuesday);

Upon executing this code, you should receive an object containing both the entry and the index in this format:

{"day": "Tuesday", "index": 2}

While this method may not be the most efficient way to retrieve both values simultaneously, it does achieve the desired outcome.

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 service being injected is not defined

Two services are involved in this scenario, with the first service being injected into the second service like so: rule.service.ts @Injectable() export class RuleService { constructor( private _resourceService: ResourceService ){} s ...

"Utilize Tuple in TypeScript to achieve high performance programming

I've been delving into TypeScript, focusing on the tuple type. As per information from the documentation, here is the definition of a tuple: A tuple type is another form of Array type that precisely knows its element count and types at specific posi ...

Mastering the art of debugging feathersjs with typescript on VS Code

I am facing an issue while trying to debug a TypeScript project with FeathersJS using VSCode. Whenever I try to launch the program, I encounter the following error: "Cannot start the program '[project_path]/src/index.ts' as the corresponding J ...

Experiencing an error when attempting to pass strings from .env.local to a new Redis instance

Encountering an issue with TypeScript while setting up a new Redis instance. I have configured an .env.local file with matching names for the redis URL and token. Below is the code snippet: import { Redis } from "@upstash/redis"; // @ts-ignore ...

The button will be disabled if any cells in the schedule are left unchecked

I am seeking help on how to dynamically disable the save button when all checkboxes are unchecked. Additionally, I need assistance with enabling the save button if at least one hour is selected in the schedule. Below is my code snippet for reference: htt ...

Insert a new item into a current array using Typescript and Angular

-This is my curated list- export const FORMULARLIST: formular[] = [ { id: 1, name: 'Jane Doe', mobileNumber: 987654, secondMobileNumber: 456789, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e1bcc0d9ec ...

Navigating through a dictionary in React TypescriptWould you like to learn

Currently, I am delving into the world of React and TypeScript. Within my journey, I have stumbled upon a dictionary representing various departments, with employee data stored in arrays. type Department = { Emp_Id: number, Name: string, Age: n ...

Having trouble utilizing Vue3 methods while utilizing the `<script setup lang="ts">` syntax

Looking to incorporate Vue into a non-Vue Class using the Composition API for a Chrome Extension project where having the entire thing as a Vue App doesn't make sense. The Vue Instance is being instantiated in the usual manner and then injected into ...

Ways to modify the CSS of an active class within a child component when clicking on another shared component in angular

In my HTML template, I am encountering an issue with two common components. When I click on the app-header link, its active class is applied. However, when I proceed to click on the side navbar's link, its active class also gets applied. I want to en ...

The argument of type 'NextRouter' cannot be assigned to the parameter of type 'Props' in this scenario

In my component, I am initializing a Formik form by calling a function and passing the next/router object. This is how it looks: export default function Reset() { const router = useRouter(); const formik = useFormik(RecoverForm(router)); return ( ...

Using Formik: When the initial value is changed, the props.value will be updated

After the initial props are updated, it is important to also update the values in the forms accordingly. export default withFormik({ mapPropsToValues: (props: Props) => { return ( { id: props.initialData.id, ...

Utilizing the power of dojo/text! directly within a TypeScript class

I have encountered examples suggesting the possibility of achieving this, but my attempts have been unsuccessful. Working with Typescript 2.7.2 in our project where numerous extensions of dijit._Widget and dijit._TemplatedMixin are written in JavaScript, w ...

Angular Lifecycle Hook - Data loading initializes after the view initialization is complete

In my component, I have loaded a firestore document and converted it into a plain js object within the constructor. However, when trying to access the field values in the template, there is a slight delay in loading them. This results in an error being dis ...

`Unresponsiveness in updating bound property after change in Angular2 child property`

Having trouble with my custom directive and ngOnChanges() not firing when changing a child property of the input. my.component.ts import {Component} from 'angular2/core'; import {MyDirective} from './my.directive'; @Component({ d ...

What is the best way to perform type checking for a basic generic function without resorting to using a cumbersome cast

Struggling with TypeScript and trying to understand a specific issue for the past few days. Here is a simplified version: type StrKeyStrVal = { [key: string]: string }; function setKeyVal<T extends StrKeyStrVal>(obj: T, key: keyof T, value: str ...

Preventing Bootstrap modal from closing when clicking outside of the modal in Angular 4

I'm working with Angular 4 and trying to prevent the model from closing when I click outside of it. Below is the code snippet I am using: <div id="confirmTaskDelete" class="modal fade" [config]=" {backdrop: 'static', keyboard: false}" ro ...

Having trouble achieving success with browser.addcommand() in webdriverIO using typescript

I tried implementing custom commands in TypeScript based on the WebdriverIO documentation, but unfortunately, I wasn't able to get it working. my ts.confg { "compilerOptions": { "baseUrl": ".", "paths": { "*": [ "./*" ], ...

Developing a user interface that filters out a specific key while allowing all other variable keys to be of the identical type

As I dive deeper into the TypeScript type system, I find myself grappling with an interface design query. Can anyone lend a hand? My goal is to craft an interface in TypeScript where certain object keys are of a generic type and all other keys should be o ...

What's the deal with TypeScript tsconfig allowing .json imports, but not allowing them in built .js files?

By including the line "resolveJsonModule": true in my project's .tsconfig file, I have successfully implemented direct importing of data from .json files. The project functions properly, even when using nodemon. However, upon building the project and ...

Find out whether the page was reloaded or accessed directly through a hyperlink

I need to find out if the page was accessed directly via a link. If it was, I need to perform a certain action. However, my current implementation is not working as intended, as even a page refresh triggers this action. Is there an alternative method to ch ...