Array indexOf and lastIndexOf in JavaScript
Level 3129 keystrokes
Uses indexOf() to find the first occurrence and lastIndexOf() to find the last occurrence.
JavaScript code
// Create an array with number 2 appearing multiple times1const nums = [1, 2, 3, 2, 4, 2, 5];// indexOf() returns the index of the FIRST occurrence// First 2 is at index 12console.log(nums.indexOf(2));// lastIndexOf() returns the index of the LAST occurrence// Last 2 is at index 53console.log(nums.lastIndexOf(2));// Returns -1 if the element is not found4console.log(nums.indexOf(9));Output
1 5 -1
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
,× 6.× 6(× 6)× 6;× 4[× 1]× 1=× 1