Filtering an array of objects with string

Filtering an Array of Objects with String

When working with TypeScript, you may often come across situations where you need to filter an array of objects based on a specific string value. In this blog post, we will explore different solutions to achieve this task.

Solution 1: Using the filter() Method

The filter() method in TypeScript allows you to create a new array with all elements that pass a certain condition. In this case, we can use it to filter an array of objects based on a specific string value.

Here’s an example:

const data = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'David', age: 35 },
];

const searchString = 'Jane';

const filteredData = data.filter((item) => item.name.toLowerCase().includes(searchString.toLowerCase()));

console.log(filteredData);

The above code will filter the data array and create a new array called filteredData that only contains objects with the name matching the searchString. The comparison is case-insensitive.

Solution 2: Using the find() Method

If you only need to find the first matching object in the array, you can use the find() method instead of filter(). The find() method returns the first element that satisfies the provided testing function.

Here’s an example:

const data = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'David', age: 35 },
];

const searchString = 'Jane';

const foundObject = data.find((item) => item.name.toLowerCase().includes(searchString.toLowerCase()));

console.log(foundObject);

The above code will find the first object in the data array that has a name matching the searchString. Again, the comparison is case-insensitive.

Solution 3: Using a for loop

If you prefer a more traditional approach, you can use a for loop to iterate through the array and manually filter the objects based on the string value.

Here’s an example:

const data = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'David', age: 35 },
];

const searchString = 'Jane';

const filteredData = [];

for (let i = 0; i < data.length; i++) {
  if (data[i].name.toLowerCase().includes(searchString.toLowerCase())) {
    filteredData.push(data[i]);
  }
}

console.log(filteredData);

The above code manually iterates through the data array, checks if each object's name matches the searchString, and adds the matching objects to the filteredData array.

These are three different solutions you can use to filter an array of objects based on a specific string value in TypeScript. Choose the one that best fits your requirements and coding style.

Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *