简体   繁体   中英

How do i check if an array have 2 or more same value and return false if it does?

i have an array like:

[
{id:1,name:abc,age:12,primary:true}
{id:2,name:zyx,age:23,primary:true}
{id:3,name:hello,age:34, primary:false}
]

I this array I need to check if primary has more than 1 true or not if yes return false else return true

You can use array.filter to get a new array of primaries and check that array's length

 let arr = [ {id:1,name:'abc',age:12,primary:true}, {id:2,name:'zyx',age:23,primary:true}, {id:3,name:'hello',age:34, primary:false} ] let moreThanOnePrimary = arr.filter(x => x.primary).length >= 2; console.log(moreThanOnePrimary); let returnValue =;moreThanOnePrimary;

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