JavaScript Linq
JavaScript Linq

Reputation: 2795

TypeScript simplest way to check if item exists in array like C# Linq Any ( using any library )

TypeScript simplest way to check if item exists in array like C# Linq Any ( using any library ). Something like

var myArray=[1,2,3,4];

var is_3_Exist=myArray.Any(x=> x==3);

Upvotes: 40

Views: 45156

Answers (6)

Cliff
Cliff

Reputation: 39

There is a TypeScript library for LINQ.

It is called ts-generic-collections-linq.

Providing strongly-typed, queryable collections such as:

  • List
  • Dictionary

Easy to use.

NPM

https://www.npmjs.com/package/ts-generic-collections-linq

Sample linq query:

let myArray=[1,2,3,4];

let list = new List(myArray);

let is_3_Exist = list.any(x => x==3);

Upvotes: 1

Tore Aurstad
Tore Aurstad

Reputation: 3816

For those who want to fiddle more with prototype to get started writing such 'extension methods':

   if (!Array.prototype.Any) {
  Array.prototype.Any = function <T>(condition: predicate<T>): boolean {
    if (this.length === 0)
      return false;
    let result: boolean = false;
    for (let index = 0; index < this.length; index++) {
      const element = this[index];
      if (condition(element)) {
        result = true;
        break;
      }
    }
    return result;
  }
}

The prototype allows you to add functionality to arrays like and call the functionality easy:

let anyEven = [5, 3, 1, 7, 3, 4, 7].Any(x => x % 2== 0); //true

Upvotes: 0

seven
seven

Reputation: 414

FIDDLE: https://jsfiddle.net/vktawbzg/

NPM: https://www.npmjs.com/package/linqscript

GITHUB: https://github.com/sevensc/linqscript

Take a look at my Github Repository. It would be great if you guys can help to improve it! https://github.com/sevensc/linqscript

Syntax:

list.Any(c => c.Name === ("Apple"))

Upvotes: 5

Nypan
Nypan

Reputation: 7246

If this is the only thing you need to do you should go for .some (with polyfill) if you however want Linq functionality for other things as well you should take a look at https://github.com/ReactiveX/IxJS.

Upvotes: 1

abahet
abahet

Reputation: 10623

You can use the findindex method :

if( myArray.findIndex(x => x === 3) >= 0) {
    // foud myArray element equals to 3
}

Upvotes: 2

basarat
basarat

Reputation: 275887

Use .some:

myArray.some(x=>x==3);

Upvotes: 59

Related Questions