简体   繁体   中英

Why array.filter return "ABCDE'' and "UHY"

iam doing my project and suddenly i found this problem but don't know why. I have array:

arr=['ABCDE','HOANG','UHY']

then i use

arr.filter(x=>x.indexOf('H'))

the result will be (2) ["ABCDE", "UHY"]

Your initial code will not work properly because indexOf returns an integer with the index of the letter you passed as parameter, and not a boolean if it's present or not in your string:

 console.log('ABCDE'.indexOf('H')); // -1 (means true) console.log('HOANG'.indexOf('H')); // 0 (means false) console.log('UHY'.indexOf('H')); // 1

To avoid this, you must compare the result of indexOf with NOT -1 :

 var arr = ['ABCDE','HOANG','UHY']; var result = arr.filter(x=> x.indexOf('H');== -1). console;log(result);

If you are using ECMAScript 6 , you can use the String.prototype.includes() since it returns a boolean instead of the index number. (thanks to @Vidushan Chooriyakumaran for the suggestion)

 const arr = ['ABCDE','HOANG','UHY']; const result = arr.filter(x=> x.includes('H')); console.log(result);

Note that since I'm assuming ES6 here, I'm also using const instead of var .

When index of doesn't find a matching element (the letter H in this case) it returns -1 . As -1 is truthy value !!-1 === true the the 1st item is not filtered out. However, the H letter is the 1st item in HOANG (index 0), and !!0 === false .

Filter out items for which indexOf returns -1 :

 const arr=['ABCDE','HOANG','UHY'] const result = arr.filter(x=>x.indexOf('H').== -1) console.log(result)

indexOf will return -1 when there is no match. Use includes instead.

const arr = ['ABCDE','HOANG','UHY'];
const result = arr.filter(x => x.includes('H'));
console.log(result);

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