K
K
KOPC18862014-10-31 16:41:12
Angular
KOPC1886, 2014-10-31 16:41:12

How to find array key by value in multidimensional array?

I wrote this code, everything works, but maybe there is a javascript function?

if($routeParams.categoryId.length != 0)
        {
            angular.forEach($rootScope.categories, function(value, key){
                 if(value.id == $routeParams.categoryId)
                 {
                    $scope.selectedCategory = $rootScope.categories[key];
                 }
            });
        }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Everlier, 2014-10-31
@Everlier

Is the array exactly multidimensional? Judging by one iteration, this is not the case, in which case the native for () will be a little faster.
In addition, there is Array.indexOf(object, from), but this is only suitable if you have a reference to the object you are looking for.
But, judging by the code, this is not your case, so you will probably have to use a loop.

K
KOPC1886, 2014-10-31
@KOPC1886

I have an array like this:

$array[0] = array('id' => 119);
$array[1] = array('id' => 120);
$array[2] = array('id' => 121);

_
_ _, 2014-10-31
@AMar4enko

There is no native function.
If you don't mind underscore or lodash then

_.find($rootScope.categories, {id: $routeParams.categoryId})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question