Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

How to Check if an Item is in an Array in JavaScript Using Array.includes() Starting From a Specified Index

// the second parameter is used to specify the index to start from when searching for an item in an array.

// The index of an array starts from 0. So the first item is 0, the second item is 1, the third item is 2, and so on.

// Here's an example to show how we can use the includes() method's second parameter:

const nums = [ 1, 3, 5, 7];
console.log(nums.includes(3,2));
// false

// The example above returned false even though we had 3 as an item in the array. Here's why:

// Using the second parameter, we told the includes() method to search for the number 3 but starting from index 2: nums.includes(3,2).

// This is the array:  [ 1, 3, 5, 7]

// Index 0 = 1.

// Index 1 = 3.

// Index 2 =  5.

// Index 3 = 7.

// So starting from the second index which is 5, we have only 5 and 7 ([5,7]) to be searched through. This is why searching for 3 from index 2 returned false.

// If you change the index to start the search from to 1 then you'd get true returned because 3 can be found within that range. That is:

const nums = [ 1, 3, 5, 7];
console.log(nums.includes(3,1));
// true
Source by www.freecodecamp.org #
 
PREVIOUS NEXT
Tagged: #How #Check #Item #Array #JavaScript #Using #Starting #From #Specified #Index
ADD COMMENT
Topic
Name
5+7 =