1

I have a $scope.arrSubThick = [1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 8, 7: 10, 8: 12, 9: 15, 10: 19] like this how to get the key of this array in script.

for eg: key of value 3 is 2 similarly 6th value key is 5

Thanks in advance

2 Answers 2

2

JavaScript doesn't have "associative arrays". It has arrays:

[1, 2, 3, 4, 5]

or objects:

{1: 2, 2: 3, 3: 4, 4: 5, 5: 6}

The second case, is what you want, then you can use:

    var looking_for = 3;
    var looking_for_key; 
    angular.forEach(values, function(value, key) {
        if(value == looking_for){
            looking_for_key = key;
        }
    });
   alert(looking_for_key);
Sign up to request clarification or add additional context in comments.

Comments

0

Array key defining like that is not possible in js. You shoud to it like this by using array of objects:

 $scope.arrSubThick = [{1: 2}, {2: 3}, {3: 4}];

Or with an single object (I guess, this fits for your needs):

$scope.arrSubThick = {1: 2, 2: 3, 3: 4};
console.log($scope.arrSubThick[1]); // 2

If you want to find key by value, do this:

$scope.arrSubThick = {
    1: 2,
    2: 3,
    3: 4
};
$scope.selected = null;
$scope.getItemByValue = function(value) {
    angular.forEach($scope.arrSubThick, function (val, key) {
        if (val == value) {
            $scope.selected = key;
        }
    });
};
$scope.getItemByValue(2);

http://plnkr.co/edit/smHJyRLsFk5GumuTGJQp?p=preview

1 Comment

i want the opposite way.like if you give 2 as input it should alert 1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.