Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Array find element by index

Finding and assigning a CategoryApi object having categoryId

export class CategoryApi {
    categoryId: number;
    name: string;
}

categories: CategoryApi[];
selectedCategory: CategoryApi;

selectedCategory = categories.findByIndex(2); //looking for categoryApi by categoryId = 2

I found this javascript option but Typescript is complaining about function

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function findCherries(fruit) { 
    return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
like image 588
Exec21 Avatar asked Dec 07 '16 02:12

Exec21


People also ask

How do you find the index of an element in an array in TypeScript?

TypeScript - Array indexOf() indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

How do you find the index of an element in an array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.


3 Answers

There is no such method findByIndex in JS, the only method is findIndex.

You can use the filter or the find method to get the item by index:

// ES2015

selectedCategory = categories.find(item => item.categoryId === 1);

// ES5

selectedCategory = categories.filter(item => item.categoryId === 1)[0];
like image 135
Bazinga Avatar answered Oct 16 '22 08:10

Bazinga


TO get specific parameter values. Use this code

this.categories.find(item => item.categoryId === 1).categoryId 

WHere categoryId can be any field you want

like image 37
ammad khan Avatar answered Oct 16 '22 06:10

ammad khan


You can use the find method:

selectedCategory = categories.find(c => c.categoryApi == 2);

The problem is, that the find function isn't listed in the typings-file.

First, ignore the error-message and try it!

Second, you could edit the typings-file:

  1. change find with filter and press F12 (go to declaration)
  2. copy this line in the typings-file and rename the function to find and the returned value to single-object instead of an array!
  3. save that file
  4. rename your back filter to find in your code..
like image 2
slaesh Avatar answered Oct 16 '22 07:10

slaesh