Is there an equivalent of "Array.None" in JS?

Viewed 13911

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

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")

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.

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)

Related