45

There's a similar question for LINQ: Is there an equivalent of None() in LINQ?

There are some boolean methods on collections / arrays:

Can I check if no elements in array match a given function callback

A possible workaround is to .filter and then check .length and make sure it's zero:

let arr = ["a","b","c"]
// make sure that no item in array = "b"
let noBs = arr.filter(el => el === "b").length === 0

3 Answers 3

78

As logically concluded by the linq example: None is the same as !Any, so you could define your own utility method like this:

const none = (arr, callback) => !arr.some(callback)

And then call like this:

const arr = ["a","b","c"]
const hasNoCs = none(arr, el => el === "c") // false
const hasNoDs = none(arr, el => el === "d") // true

Demo in Stack Snippets

const none = (arr, callback) => !arr.some(callback)

const arr = ["a","b","c"]

const hasNoCs = none(arr, el => el === "c") // false
const hasNoDs = none(arr, el => el === "d") // true

console.log({hasNoCs, hasNoDs})

Sign up to request clarification or add additional context in comments.

Comments

10

Not at the moment

At the moment I'm using an Array.some() and then negating the whole thing

Personally I think an Array.none function would be awesome

You could request it to be added to the next release of ECMA. It looks like a bit of a process to say the least but if we wanted to get this added to ECMA this would be the way.

4 Comments

Warning: not every is not the same as none!
oh yes I think i meant ! Array.any Thanks for pointing that out, will update my answer
I think you mean Array.some (to my knowledge there's no any alias in JS).
!Array.some(...) will be true when every entry is falsy, and false otherwise
2

Liked the @KyledMit approach. On the similar lines, using the findIndex is another way. (find may not be reliable as we can not check on return value).

const arr = ["a","b","c"]

const noBs = arr.findIndex(el => el === "b") < 0;

console.log(noBs)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.