35

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);
JavaScript Linq
  • 2,605
  • 3
  • 13
  • 12
  • 2
    possible duplicate of [Determine whether an array contains a value](http://stackoverflow.com/questions/1181575/determine-whether-an-array-contains-a-value) – Maximillian Laumeister Aug 17 '15 at 06:22

6 Answers6

55

Use .some:

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

basarat
  • 261,912
  • 58
  • 460
  • 511
5

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"))
seven
  • 414
  • 4
  • 12
  • Could you please tell me how to link your linqscript to already existing TS files? And what should I do to call this stuff from my code? – user216652 Apr 21 '17 at 09:16
  • i made a npm package, get it there: `npm install linqscript` https://www.npmjs.com/package/linqscript You need to import the namespace. See the Readme for more infos. – seven Apr 26 '17 at 19:13
  • Ok, I saw the package but don't quite understand how to use it from my TS code. Could you please drop a line of details? – user216652 May 05 '17 at 20:03
2

You can use the findindex method :

if( myArray.findIndex(x => x === 3) >= 0) {
    // foud myArray element equals to 3
}
abahet
  • 10,355
  • 4
  • 32
  • 23
1

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.

Nypan
  • 6,980
  • 3
  • 21
  • 28
1

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);
Cliff
  • 41
  • 2
0

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

Tore Aurstad
  • 3,189
  • 1
  • 27
  • 22