Typescript Array find element by index

Exec21 picture Exec21 · Dec 7, 2016 · Viewed 82.1k times · Source

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 }

Answer

Bazinga picture Bazinga · Dec 7, 2016

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];