Useful Array Functions in JavaScript and C#
How to check if array contains a specific item
To check if an object or item is contained in a JavaScript array, you can use the includes
function, like so:
const customerIds = [1, 2, 3, 4, 5];
console.log('IsIncludedInArray', customerIds.includes(3));
To do the same thing in C#, you can use the Contains
or Any
LINQ method, like so:
var customerIds = new int[5] { 1, 2, 3, 4, 5};
Console.WriteLine("IsIncludedInArray " + customerIds.Contains(3));
Console.WriteLine("IsIncludedInArray " + customerIds.Any(n => n == 3));
How to filter out contents in an array
To filter out the contents of an array in JavaScript, you can use the filter
function., like so:
const customerIds = [1, 2, 3, 4, 5];
const filteredCustomerIds = customerIds.filter(n => n <= 3);
console.log('Filtered CustomerIds', filteredCustomerIds);
To do the same thing in C#, you can use the Where
LINQ method.
var customerIds = new int[5] { 1, 2, 3, 4, 5};
var filteredCustomerIds = customerIds.Where(n => n <= 3);
foreach (var n in filteredCustomerIds)
{
Console.WriteLine(n);
}
Tags: #JavaScript #CSharp #DotNet
Discuss... or leave a comment below.