Reputation: 2795
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
Reputation: 39
There is a TypeScript library for LINQ.
It is called ts-generic-collections-linq.
Providing strongly-typed, queryable collections such as:
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
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
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
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
Reputation: 10623
You can use the findindex method :
if( myArray.findIndex(x => x === 3) >= 0) {
// foud myArray element equals to 3
}
Upvotes: 2