Поиск элемента в массиве typescript

How do I find an array item with TypeScript? (a modern, easier way)

Is there a canonical way to find an item in an array with TypeScript?

  • «item» could be a JavaScript object, or almost anything else. The example above happens to be to find plain ol’ native JS objects, but many scenarios exist.
  • «canonical» is just a fancy way in Computer Science (and other fields) to say «general accepted rule or standard formula» (remember everyone here didn’t know that at some point)
  • This is not about new features. Any version of JS could do this. However the form to do so gets less and less appealing the farther you go back in time.
  • TypeScript roadmap for reference.

And what kind of object? I don’t see an example here. Also, TypeScript is just annotated JS. You can write vanilla JS in TypeScript and it will still run.

@Joseph the Dreamer Updated example to show searching for native JS objects. I know TS supports ES5 code, the point is that the example from ES6 is much nicer, and TS is supposedly on the path of implementing ES6 features.

Читайте также:  Class object python init

@Alexander Abakumov thanks for the edit. Let’s keep improving! Unless you see a disadvantage, I’m going to add to your edits, to address the word «object» within the body text.

@whitneyland: Sure! Sorry, I should have been changed to the ‘item’ within the body text as well, not only the title.

@Joseph the Dreamer responding to your concerns back when, I should have noted I endeavored to address all of them, and it’s now all reflected in edits to the question. If I missed anything, shout out. Thx for the feedback.

5 Answers 5

For browsers that haven’t implemented it, a polyfill for array.find . Courtesy of MDN.

if (!Array.prototype.find) < Array.prototype.find = function(predicate) < if (this == null) < throw new TypeError('Array.prototype.find called on null or undefined'); >if (typeof predicate !== 'function') < throw new TypeError('predicate must be a function'); >var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) < value = list[i]; if (predicate.call(thisArg, value, i, list)) < return value; >> return undefined; >; > 

You need to extend the open Array interface to include the find method.

interface Array  < find(predicate: (search: T) =>boolean) : T; > 

When this arrives in TypeScript, you’ll get a warning from the compiler that will remind you to delete this.

The variable x will have the expected type.

var x = [< "id": 1 >, < "id": -2 >, < "id": 3 >].find(myObj => myObj.id < 0); 

Источник

Поиск элемента в массиве typescript

Last updated: Jan 20, 2023
Reading time · 3 min

banner

# Table of Contents

# Find the first object in an array that matches a condition in TS

To find an object in an array:

  1. Use the Array.find() method to iterate over the array.
  2. Check if each object meets a condition.
  3. The find method will return the first matching object.
Copied!
const arr = [ id: 1, country: 'Mexico' >, id: 2, country: 'Germany' >, id: 3, country: 'Mexico' >, ]; const found = arr.find((obj) => return obj.id === 1; >); // 👇️ console.log(found);

The function we passed to the Array.find method gets called with each element (object) in the array until it returns a truthy value or iterates over the entire array.

On each iteration, we check if the id property of the object is equal to 1 .

This is very convenient when you only need to get the first object that matches the specific condition.

There are no wasted iterations because once the condition is met, the find() method short-circuits and returns the object.

If the callback function we passed to the find method never returns a truthy value, the find() method returns undefined .

Copied!
const arr = [ id: 1, country: 'Mexico' >, id: 2, country: 'Germany' >, id: 3, country: 'Mexico' >, ]; // 👇️ const found: | undefined const found = arr.find((obj) => return obj.id === 1; >);

Notice that the type of the found variable is either an object or undefined .

You can use a type guard to narrow down the type to be able to access properties on the object.

Copied!
const arr = [ id: 1, country: 'Mexico' >, id: 2, country: 'Germany' >, id: 3, country: 'Mexico' >, ]; // 👇️ const found: | undefined const found = arr.find((obj) => return obj.id === 1; >); if (found) // ✅ TypeScript now knows that found is an object // and not undefined console.log(found.country); // 👉️ Mexico >

TypeScript can safely infer the type of the found variable to be an object in the if block.

# Find all Objects in an Array that match a condition in TS

To find all objects in an array that match a condition:

  1. Use the filter() method to iterate over the array.
  2. Check if each object matches a condition.
  3. The filter method will return a new array containing the objects that match the condition.
Copied!
const arr = [ id: 1, country: 'Mexico' >, id: 2, country: 'Germany' >, id: 3, country: 'Mexico' >, ]; const filtered = arr.filter((obj) => return obj.country === 'Mexico'; >); // 👇️ [, ] console.log(filtered);

The function we passed to the Array.filter method gets called with each element (object) in the array.

The filter() method returns a new array that only contains the elements that meet the condition.

Note that the filter method will iterate over the entire array, regardless of how many times the condition is met.

This way, we are able to get multiple objects that meet a specific condition from an array of objects.

If the callback function we passed to the filter method never returns a truthy value, the filter method returns an empty array.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

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

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?

i made a npm package, get it there: npm install linqscript npmjs.com/package/linqscript You need to import the namespace. See the Readme for more infos.

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?

You can use the findindex method :

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

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.

There is a TypeScript library for LINQ.

It is called ts-generic-collections-linq.

Providing strongly-typed, queryable collections such as:

let myArray=[1,2,3,4]; let list = new List(myArray); let is_3_Exist = list.any(x => x==3); 

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

 if (!Array.prototype.Any) < Array.prototype.Any = function (condition: predicate): 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

Источник

Оцените статью