26

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
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
KyleMit
  • 30,350
  • 66
  • 462
  • 664

4 Answers4

55

As logically concluded by the linq example

None is the same as !Any, so you could define your own extension method as follows:

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

And then call like this:

let arr = ["a","b","c"]
let noBs = none(arr, el => el === "b")

Or if you want to extend Array.proto, you can add the following method:

Object.defineProperty(Array.prototype, 'none', {
    value: function (callback) { return !this.some(callback) }
});

Then call like this:

let arr = ["a","b","c"]
let noBs = arr.none(el => el === "b")
KyleMit
  • 30,350
  • 66
  • 462
  • 664
8

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.

Max Carroll
  • 4,441
  • 2
  • 31
  • 31
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)
Siva K V
  • 10,561
  • 2
  • 16
  • 29
0

If it's an array with scalar values, you can use Array.prototype.includes()

const arr = ["a", "b", "c"]
const includesB = arr.includes("b")

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Paul Clark
  • 81
  • 1
  • 3