Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

There are some boolean methods on collections / arrays:

  • Array.some (similar to linq.Any)
  • Array.every (similar to linq.All)

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
like image 839
KyleMit Avatar asked Jul 15 '20 02:07

KyleMit


2 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")
like image 191
KyleMit Avatar answered Sep 22 '22 19:09

KyleMit


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.

like image 27
Max Carroll Avatar answered Sep 22 '22 19:09

Max Carroll