英文:
Typescript filter give me array of values that don't meet condition
问题
非常新于TypeScript,在下面的数组上使用filter
函数,我期望filter.length
的值为1,因为我们有一个角色是Principal。但是我收到的是2,因为它正在检查有多少个角色不包含该索引,我该如何检查至少有一个值为Principal的角色数组有多少个?
英文:
Very new to typescript, using the filter function on below array, I would expect filter.length to be 1 as we have one person with a role of Principal. but I receive 2 as it is checking how many roles do not have that index, how can i check how many role arrays contain at least 1 value of Principal?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const people = [
{
"roles": [
"Claimant"
],
"name": "mick"
},
{
"roles": [
"Principal"
],
"name": "paddy"
},
{
"roles": [
"Claimant"
],
"name": "bob"
}
]
const filter = people.filter((obj)=> obj.roles.indexOf('Principal') )
console.log(filter.length)
<!-- end snippet -->
答案1
得分: 2
使用 Array#includes
替代,它返回一个布尔值,指示元素是否存在。
Array#indexOf
返回元素的索引。第一个元素的索引是 0
,它是假值,所以 filter
不会保留该元素。
英文:
Use Array#includes
instead, which returns a boolean indicating if the element was present.
Array#indexOf
returns the index of the element. The first element would be index 0
, which is falsy, so filter
does not keep the element.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const people=[{roles:["Claimant"],name:"mick"},{roles:["Principal"],name:"paddy"},{roles:["Claimant"],name:"bob"}];
const filter = people.filter((obj)=> obj.roles.includes('Principal'))
console.log(filter.length);
<!-- end snippet -->
答案2
得分: 2
indexOf
返回 -1 表示没有匹配,所以您要使用 obj.roles.indexOf('Principal') > -1
。
英文:
indexOf
returns -1 for a non-match, so you want to use obj.roles.indexOf('Principal') > -1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论