Open In App

How to get the Index of an Array based on a Property Value in TypeScript ?

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Getting the index of an array based on a property value involves finding the position of an object within the array where a specific property matches a given value. The below approaches can be used to accomplish the task.

Using Array.findIndex()

In TypeScript, Array.findIndex() is employed to discover the index of the first array element that satisfies a specified condition defined by a callback function. It returns the index or -1 if not found.

Syntax:

array.findIndex(function(currentValue, index, arr), thisValue);

Example: The below code implements the findIndex() method to find the index of array based on its value.

Javascript
interface Person {
    id: number;
    name: string;
}

const array: Person[] = [
    { id: 1, name: "Radha" },
    { id: 2, name: "Megha" },
    { id: 3, name: "Nikita" },
];

const result1: number = array.
    findIndex(item => item.id === 2);
console.log("Index:", result1);

const result2: number = array.
    findIndex(item => item.name === "Nikita");
console.log("Index:", result2);

Output:

Index: 1
Index: 2

Using reduce() method

In this approach, the reduce() method iterates over a Person array, searching for an object with a specific id and name. It accumulates the index using a callback function, providing flexibility for custom search conditions.

Syntax:

array.reduce( 
    function(total, currentValue, currentIndex, arr), 
    initialValue )

Example: The below code implements the reduce() method to find the index of the specified value.

Javascript
interface Person {
    id: number;
    name: string;
}

const array: Person[] = [
    { id: 1, name: "Radha" },
    { id: 2, name: "Megha" },
    { id: 3, name: "Nikita" },
];

const findbyId: number = 3;
const result1: number = array.reduce(
    (acc: number, item: Person, index: number) =>
    (item.id === findbyId ? index : acc), -1);

console.log("Index:", result1);

const findbyName: string = "Nikita";
const result2: number = array.reduce(
    (acc: number, item: Person, index: number) =>
    (item.name === findbyName ? index : acc), -1);

console.log("Index:", result2);

Output:

Index: 1
Index: 2

Using for loop

In this approach, for loop iterates through each element in the array. Within the loop, it checks if the id property of the current element matches the target ID. If a match is found, it stores the index and breaks out of the loop.

Example: The below code uses a for loop to find the index of the specified value.

Javascript
interface Person {
    id: number;
    name: string;
}

const array: Person[] = [
    { id: 1, name: "Radha" },
    { id: 2, name: "Megha" },
    { id: 3, name: "Nikita" },
];

const findbyId: number = 3;
const findbyName: string = "Nikita";

let ind1: number = -1;
let ind2: number = -1;

for (let i = 0; i < array.length; i++) {
    if (array[i].id === 2 ) {
        ind1 = i;
    }
    if (array[i].name === "Nikita" ) {
        ind2 = i;
    }
}

console.log("Index:", ind1);
console.log("Index:", ind2);

Output:

Index: 1
Index: 2

Using a Custom Function

Using a custom function, the TypeScript code iterates through an array of objects, comparing a specified property value and returning the index if found, or -1 otherwise.

Syntax

const getIndexByProperty = (array: Person[], property: keyof Person, value: any): number => {
    for (let i = 0; i < array.length; i++) {
        if (array[i][property] === value) {
            return i;
        }
    }
    return -1; // Return -1 if the value is not found
};

Example: In this example we defines a function getIndexByProperty that returns the index of an object in an array based on a specified property value.

JavaScript
const getIndexByProperty = (array: Person[], 
    property: keyof Person, value: any): number => {
    for (let i = 0; i < array.length; i++) {
        if (array[i][property] === value) {
            return i;
        }
    }
     // Return -1 if the value is not found
    return -1;
};

interface Person {
    id: number;
    name: string;
}
 
const array: Person[] = [
    { id: 1, name: "Nikunj" },
    { id: 2, name: "Dhruv" },
    { id: 3, name: "Yash" },
];
 
console.log("Index:", getIndexByProperty(array, 'id', 2));
console.log("Index:", getIndexByProperty(array, 'name', "Nikunj"));

Output:

Index: 1
Index: 0


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads