2
 var array = [{"one":1, "two":2},{"one":3, "two":4}];

            var result = array.findIndex(function (value) {
                if (value === 2) {
                    return false;
                }
                return true;
            });

            console.log(result); 

i keep getting '0' in the console. how should i change (value ===2) ? i have tried change to (value === {"two":2}) but still return '0'.

is there any other array method that suitable ?

9
  • 2
    Because you are doing return true in every case. Also what does value === 2 means. value will be an object Commented Jun 6, 2017 at 6:49
  • which property do you like to check? there is no valuein the array. Commented Jun 6, 2017 at 6:49
  • 1
    value will never be 2 it will be either {"one":1, "two":2} or {"one":3, "two":4} Commented Jun 6, 2017 at 6:50
  • 1
    put a console.log into your findindex callback before the if()..and print the value passed to the callback. You might get some understanding as to what you the value is and what you are checking it with. Commented Jun 6, 2017 at 6:52
  • @JaromandaX i just want the index of {"one":1, "two":2} to show how should i change if (value === 2) ? Commented Jun 6, 2017 at 6:53

2 Answers 2

10

You need to check one of the properties of the objects of the array. Then return the result of the check.

var array = [{ one: 1, two: 2 }, { one: 3, two: 4 }],
    result = array.findIndex(function(object) {
        return object.two === 2;
    });

console.log(result);

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

6 Comments

which, ironically, will also result in 0 being output - amazed the OP thought 0 was incorrect :p
Oh, I wasn't disagreeing with your answer :p
sorry for asking @NinaScholz if the result less that zero means that it not match right ?
right it returns -1, because this number is not a real index of an array.
thank you so much i'm still learning.. and u help a lot.. again thank u @NinaScholz
|
0

Its first argument of the array .change with value.two .its object property not a array

var array = [{"one":1, "two":2},{"one":3, "two":4}];
            var result = array.findIndex(function (value) {
                               return value.two == 2;
            });
            console.log(result); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.