Difference Between indexOf and findIndex function of array

后端 未结 7 597
暗喜
暗喜 2020-11-30 19:42

I am confused between the difference between the two function indexOf and find Index in an array.

The documentation says

findIndex - Returns

7条回答
  •  时光说笑
    2020-11-30 20:20

    Simple - What kind of array structure are you using?

    • If array of objects, findIndex();
    • Else, indexOf().

    "I want to find the index in an array of objects, with the key of "Orange".

    let fruits = [
       { type: "Apple", quantity: 9 },
       { type: "Banana", quantity: 2},
       { type: "Orange", quantity: 8},
       { type: "Pear", quantity: 777}
    ];
    
    let myIndex = fruits.findIndex(fruit => fruit.type === "Orange"); // Returns 2.
    

    "I want to find the index in a simple array".

    let fruits = [ "Apple", "Banana", "Pear", "Orange"];
    
    let index = fruits.indexOf("Orange"); // Returns 3.
    

提交回复
热议问题