0

That's was surprise, but simple function array.IndexOf is not working.

$scope.nextProduct = function (pos, item) {
    switch (pos) {
        case 0: product = $scope.Menu[0].Breakfast
            break
        case 1: product = $scope.Menu[0].Lunch
            break
        case 2: product = $scope.Menu[0].BeforTraining
            break
        case 3: product = $scope.Menu[0].AfterTraining
            break
        case 4: product = $scope.Menu[0].Dinner
            break
        default: product = $scope.Menu[0].Breakfast
            break
    }
    var index = product.indexOf(item.Name);
    product[index - 1].IsSelect = false;
    product[index + 1].IsSelected = true;
}

indexOf return -1 but I'm completely sure that the item exist in array. What can be wrong here?enter image description here

4
  • No, the object doesn't exist: an object whose "name" is the same as item.Name exists, that's very different. Commented Jun 21, 2016 at 13:31
  • Well, but item.Name it's just string, isn't it? Commented Jun 21, 2016 at 13:32
  • 2
    Your searching an array of objects for a string, how does it know you want to match the .Name property? Commented Jun 21, 2016 at 13:32
  • Have you tried to debug this in the console? If you set a breakpoint on line 211. You can then execute JS in the console. This will be the quickest way to debug your problem. Commented Jun 21, 2016 at 13:34

1 Answer 1

2

By this expression you are searching for a string in object array.

product.indexOf(item.Name);

Instead you should run:

var res = product.filter(function(elem){
    return elem.Name == someValue
})

this returns array matching your value

Sign up to request clarification or add additional context in comments.

5 Comments

map would be more suitable as OP needs the index. For example: var index = product.map(function(p) { return p.Name; }).indexOf(item.Name);
@OscarBarrett, yes, that's exactly what I need. Please add comment as answer.
@asdf_enel_hak, yes, your solution is working but that's not what I need.
@andrey.shedko yep I see
@andrey.shedko I would have added my comment as an answer, however this question has been marked as a duplicate and is therefore locked.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.