In my PHP code, I am able to obtain the key from an array by searching for a specific value.
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
However, as I delve into learning JavaScript, I have been unable to find a solution to achieve the same functionality. As a beginner in JavaScript programming, I'm facing some challenges.
What is the method to retrieve the key based on a given value inside an array in JavaScript?
I've attempted using methods like .indexOf() or .findIndex() without success.
var array = [];
array['key'] = 'Value';
array['car'] = 'Ferrari';
array['car2'] = 'BMW';
console.log(key='Ferrari'??);
If the value is 'Ferrari', how can I return the key 'car'?
Furthermore, should I utilize Arrays or Classes to address this issue? Is it feasible to fetch the key of a Class?
var pessoas = {'car': 'Ferrari', 'car2':'BMW'};