简体   繁体   中英

Find element in array using array-includes from npm

How would I go about finding the index or element in an array that contains something I'm looking for?

When I tried using includes() i get

m.includes() is not a function

I've installed array-includes from NPM but I still can't figure out how to do it. Example of what I want:

Make an array of strings eg. ['apple', 'orange', 'kiwi']
Check each of the elements for If they contain 'orange'
Have it return either the element itself, or the index of the element in the 
array.

I've tried:

pinmsgs = pinmsgs.filter(includes(pinmsgs, 'countdownTill'))

And this is the error:

(node:3256) UnhandledPromiseRejectionWarning: TypeError: fn is not a function
at Map.filter (C:\Users\oof\Desktop\VVbot - kopie (2) - kopie\node_modules\d
iscord.js\src\util\Collection.js:289:11)
at message.guild.channels.find.fetchPinnedMessages.then (C:\Users\oof\Deskto
p\VVbot - kopie (2) - kopie\bot.js:54:37)
at process._tickCallback (internal/process/next_tick.js:68:7)

I also need it to work for when i put in only a part of what I'm looking for - eg. if I look for appl it will still output apple

You can use find if you want to find the element. Or findIndex if you want to find the index

 const array = ['apple', 'orange', 'kiwi'], item = "orange"; const found = array.find(a => a.includes(item)) const index = array.findIndex(a => a.includes(item)) // if you want to find if item exists in the array const fullMatchIndex = array.indexOf(item) console.log(found) console.log(index) console.log(fullMatchIndex) 

There are bunch of function you can use

  • Using indexOf , returns the index or -1 if not found
const a = ['orange', 'apple', 'kiwi'];
console.log(a.indexOf('apple'));
// 1
  • You can use filter to return array of item that matches certain condition
const a = ['orange', 'apple', 'kiwi', 'apple'];
console.log(a.filter(x => x === 'apple'));
// ['apple', 'apple']
  • You can use find to return first value of matched item or returned undefined if not found
const a = ['orange', 'apple', 'kiwi', 'apple'];
console.log(a.find(x => x === 'apple'));
// apple

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