How to get the Index of an Array based on a Property Value in TypeScript ?
Last Updated :
16 Apr, 2024
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
Similar Reads
How to Sort Objects in an Array Based on a Property in a Specific Order in TypeScript ?
Sorting objects in an array based on a specific property is a common task in software development. TypeScript, with its static typing and powerful features, provides various approaches to accomplish this task efficiently. The below approaches can be used to sort an array of objects in properties. Ta
3 min read
How to Sort an Array of Object using a Value in TypeScript ?
Sorting an array of objects using a value in TypeScript pertains to the process of arranging an array of objects in a specified order based on a particular property or value contained within each object. The below approaches can be used to sort an array of objects using a value in TypeScript: Table
3 min read
How to Get an Object Value By Key in TypeScript
In TypeScript, we can get an object value by key by accessing the specific properties within the objects of the dynamic type. This can be done using Dot Notation, Bracket Notation, and Optional Chaining. In this article, we will explore all these approaches along with their implementation in terms o
5 min read
How to Sort an Array Having Optional Properties in TypeScript ?
Sorting an array with optional properties in TypeScript involves arranging its elements based on a primary property, with fallbacks to secondary properties or default sorting criteria if the primary property is absent. Below are the approaches used to sort an array having optional properties in Type
5 min read
How to Sort an Array of Objects with Null Properties in TypeScript ?
Sorting an array of objects in TypeScript involves arranging objects based on specified properties. When dealing with null properties, ensure consistency by placing them either at the start or end of the sorted array to maintain predictability in sorting outcomes. Below are the approaches used to so
5 min read
How to move Duplicate to First Index in an Array of Objects in TypeScript ?
To efficiently rearrange an array of objects in TypeScript, moving duplicates to the first index, The approach is first to identify the duplicate within the array, then to remove the duplicate from its current position in the array then at last to re-insert the duplicate at the first index of the ar
7 min read
How to Specify that a Class Property is an Integer in TypeScript ?
Specifying that a class property is an integer in TypeScript involves using type annotations or specific TypeScript features to define the data type of the property. Below are the approaches used to specify that a class property is an integer in TypeScript: Table of Content By using Type AnnotationB
2 min read
How to Get Index of the Max Value in Array of Objects ?
When dealing with arrays of objects in JavaScript, it's common to need the index of the object with the maximum value based on a certain property. Below are the approaches to get the index of the max value in an array of objects: Table of Content Using a LoopUsing Array.reduce() MethodUsing a LoopTh
2 min read
How to Sort an Array of Objects by String Property value in Angular ?
An Object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In this article, we will learn how to Sort an array of objects by string property value in Angular. He
3 min read
How to Convert a Set to an Array in TypeScript ?
A Set in TypeScript is used to create a particular type of list that does not contain duplicate elements. If any element is repeated more than once it will automatically remove the duplicate existence and consider it only once in the list. In this article, we will convert these types of lists into a
5 min read