Reputation: 917
I'm stuck with return a value using Array.map in Angular 2 So what am I missing here?
export class TabsPage {
@ViewChild(SuperTabs) superTabs: SuperTabs;
public rootTab: string = 'ProductListPage';
public categories: Array<any>;
public collection_id: number;
public selectedindex: any;
private getArrayIndex(source, target) {
source.map((element, index) => {
if (element.attrs.collection_id === target) {
// Returns the Value i need
console.log('i: ', index);
return index;
}
});
}
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public shopifyClientProvider: ShopifyClientProvider,
private superTabsCtrl: SuperTabsController,
) {
this.categories = navParams.get('collections');
this.collection_id = navParams.get('collection_id');
this.selectedindex = this.getArrayIndex(this.categories, navParams.get('collection_id'));
// Returns undefined
console.log('Index ', this.selectedindex);
}
}
Upvotes: 0
Views: 385
Reputation: 34553
You can use findIndex() to do this in pretty short order:
I don't know exactly what your data looks like, but given an array:
const target = 2;
const source = [
{
attrs: {
collection_id: 1
}
},
{
attrs: {
collection_id: 2
}
},
{
attrs: {
collection_id: 3
}
},
];
const index = source.findIndex(element => element.attrs.collection_id === target);
would return 1
for the index. If the index isn't found, -1
will be returned.
Plunkr: https://plnkr.co/edit/5B0gnREzyz6IJ3W3
Hope that helps you out.
Upvotes: 1
Reputation: 917
Looks like Typescript breaks the return. With this modification i get the desired Value:
private getArrayIndex(source, target) {
let found: number;
source.map((element, index) => {
if (element.attrs.collection_id === target) {
console.log('i: ', index);
found = index;
}
});
return found;
}
Upvotes: 0
Reputation: 9687
I know this question is already answered but I have one solution for this same.
.ts file code
private getArrayIndex(source, target) {
let indx = -1;
source.map((element, index) => {
if (element.attrs.collection_id === target) {
// Returns the Value i need
console.log('i: ', index);
indx = index;
}
});
return indx;
}
Upvotes: 2