Typescript中的filter给我一个不满足条件的值数组。

huangapple go评论147阅读模式
英文:

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 = [
    {
        &quot;roles&quot;: [
            &quot;Claimant&quot;
        ],
        &quot;name&quot;: &quot;mick&quot;
    },
    {
        &quot;roles&quot;: [
            &quot;Principal&quot;
        ],
        &quot;name&quot;: &quot;paddy&quot;
    },
    {
        &quot;roles&quot;: [
            &quot;Claimant&quot;
        ],
        &quot;name&quot;: &quot;bob&quot;
    }
]

			const filter = people.filter((obj)=&gt; obj.roles.indexOf(&#39;Principal&#39;) )
			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:[&quot;Claimant&quot;],name:&quot;mick&quot;},{roles:[&quot;Principal&quot;],name:&quot;paddy&quot;},{roles:[&quot;Claimant&quot;],name:&quot;bob&quot;}];
const filter = people.filter((obj)=&gt; obj.roles.includes(&#39;Principal&#39;))
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(&#39;Principal&#39;) &gt; -1

huangapple
  • 本文由 发表于 2023年3月9日 23:52:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687013.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定