I have an array of objects, and an array of acceptable return values for a particular method. How do I reduce the array of objects to only those whose method in question returns a value in my array of acceptable values?
Right now, I have this:
my @allowed = grep {
my $object = $_;
my $returned = $object->method;
grep {
my $value = $_;
$value eq $returned;
} @acceptableValues;
} @objects;
The problem is that this is a compound loop, which I'd like to avoid. This program is meant to scale to arbitrary sizes, and I want to minimize the number of iterations that are run.
What's the best way to do this?
Using List contains() method. We can use Arrays class to get the list representation of the array. Then use the contains() method to check if the array contains the value.
The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.
Use forEach() to find an element in an array The Array.
You could transform the accepted return values into a hash
my %values = map { $_ => 1 } @acceptedValues;
And grep
with the condition that the key exists instead of your
original grep:
my @allowed = grep $values{ $_->method }, @objects;
Anyway, grep
is pretty fast in itself, and this is just an idea of a
common approach to checking if an element is in an array. Try not to
optimize what's not needed, since it would only be worth in really big
arrays. Then you could for example sort the accepted results array and
use a binary search, or cache results if they repeat. But again, don't
worry with this kind of optimisation unless you're dealing with hundreds
of thousands of items — or more.
Elements supposed to be present in given arrays seems unique. So, I will make a hash containing the count of elements from both arrays. If there is any element with count greater than 1, it means its present in both the arrays.
my %values;
my @allowed;
map {$values{$_}++} (@acceptableValues, @objects);
for (keys %values) {
push @allowed, $_ if $values{$_} > 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With