Index Of / Last Index Of
indexOf(value)¶
- Returns the first index of the object being sought, or
-1if it does not exist in the array. Searches from beginning to end of the array.
let obj = {name : 'test'};
let arr = [1,2,3,'kiwi', obj];
arr.indexOf(3); // 2
arr.indexOf('kiwi'); // 3
arr.indexOf(obj); // 4
arr.indexOf('not found'); // -1
lastIndexOf(value)¶
- Returns the last index of the object being sought, or
-1if it does not exist in the array. Searches from the end to the beginning of the array.
let arr = [1,2,3,4,3,2,1];
arr.lastIndexOf(1); // 6
arr.lastIndexOf(2); // 5
arr.lastIndexOf(3); // 4
arr.lastIndexOf('not found'); // -1
Skill Drill¶
Create the following array:
let arr = ["Apple", "Banana", "Coconut", "Apple"];Write a function
containsthat usesindexOfto determine if the value is in the array or not.Use the
lastIndexOffunction onarrto determine at what index the string"Apple"is stored.