1//indexOf - JS method to get index of array element.
2// Returns -1 if not found
3
4var colors=["red","green","blue"];
5var pos=colors.indexOf("blue");//2
6
7//indexOf getting index of sub string, returns -1 if not found
8
9var str = "We got a poop cleanup on isle 4.";
10var strPos = str.indexOf("poop");//9
11
12//Eg with material ui
13
14<Checkbox
15 checked={value.indexOf(option) > -1}
16 value={option}
17/>
1var indices = [];
2var array = ['a', 'b', 'a', 'c', 'a', 'd'];
3var element = 'a';
4var idx = array.indexOf(element);
5while (idx != -1) {
6 indices.push(idx);
7 idx = array.indexOf(element, idx + 1);
8}
9console.log(indices);
10// [0, 2, 4]
11
1//indexOf getting index of array element, returns -1 if not found
2var colors=["red","green","blue"];
3var pos=colors.indexOf("blue");//2
4
5//indexOf getting index of sub string, returns -1 if not found
6var str = "We got a poop cleanup on isle 4.";
7var strPos = str.indexOf("poop");//9
1
2var str = "Please locate where 'locate' occurs!";
3
4var ind1 = str.indexOf("locate"); // return location of first value which founded
5var ind2 = str.lastIndexOf("locate"); // return location of last value which founded
6var ind3 = str.indexOf("locate", 15); // start search from location 15 and then take first value which founded
7var ind4 = str.search("locate");
8//The search() method cannot take a second start position argument.
9//The indexOf() method cannot take powerful search values (regular expressions).
10
11document.write("<br>" + "Length of string:", len);
12document.write("<br>" + "indexOf:", ind1);
13document.write("<br>" + "index of last:", ind2);
14document.write("<br>" + "indexOf with start point:", ind3);
15document.write("<br>" + "search:", ind4);
1// for dictionary case use findIndex
2var imageList = [
3 {value: 100},
4 {value: 200},
5 {value: 300},
6 {value: 400},
7 {value: 500}
8];
9var index = imageList.findIndex(img => img.value === 200);
1const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
2
3const searchTerm = 'dog';
4const indexOfFirst = paragraph.indexOf(searchTerm);
5
6console.log(`The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`);
7// expected output: "The index of the first "dog" from the beginning is 40"
8
9console.log(`The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}`);
10// expected output: "The index of the 2nd "dog" is 52"
11