简体   繁体   中英

findIndex Array method in TypeScript

I'm very new to Angular 4 development. I encounter someArray.findIndex() is not a function. How to add this .findIndex() javascript function in TypeScript.

I'm building a calendar component, following function gives me error

WEBPACK_IMPORTED_MODULE_2_lodash .findIndex is not a function at CalendarComponent.isSelected (calendar.component.ts:4

isSelected(date: moment.Moment): boolean {
    return _.findIndex(this.selectedDates, (selectedDate) => {
      return moment(date).isSame(selectedDate.mDate, 'day');
    }) > -1;
  }

Thank you so much.

It's not about Typescript. Javascript functions are included in Typescript. You are trying to use Lodash function. Make sure that you installed and imported it on top of the file:

import _ from 'lodash';

or just use Javascript function:

isSelected(date: moment.Moment): boolean {
    return this.selectedDates.findIndex((selectedDate) => {
      return moment(date).isSame(selectedDate.mDate, 'day');
    });
}

You are calling findIndex method of _. You are either using UnderscoreJS or Lodash .

As the error says WEBPACK_IMPORTED_MODULE_2_lodash.findIndex is not a function It means you are using lodash.

Import lodash library and it will work.

import _ from 'lodash';

selectedDate = arrayName.find(item => item.date === searchingdate);

you can use indexOf

[1,2,3,4,5].indexOf(1) //return 0
[1,2,3,4,5].indexOf(5) //return 4
[1,2,3,4,5].indexOf(6) //return -1
[1,2,3,4,5].indexOf(0) //return -1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM