Wednesday, April 4, 2018

Array search elements

Actually lot of methods there for searching in an array.we can see those all later on next chapter.

Here we are going to see the below three methods.

      1. indexOf

      2. lastIndexOf 

      3. includes

Generally indexOf function means, you would have thought its working based on characters. But java script, here not the case. Its an item in java script.

A short intro about these all function. Let see...

Syntax:
arr.indexOf(item , from)

It returns the position of the first occurrence of a specified value in a string. If unable to find will return -1.

item - Its specifies what you are searching...
from - Its Optional. Default 0. At which position to start the search(item).


Syntax:
arr.lastIndexOf(item, from)

It looks from right to left. Means, returns the position of the last occurrence of a specified value in a string. If unable to find will return -1.

item - The string(item) what you are going to search.
from - Its Optional. The position where to start the search.

Syntax:
arr.includes(item, from)

It checks whether a string contains the characters of a specified string. This method returns true if the string contains the characters, and false if not able to find.

item - The string, what you are going to search.
from - Its an optional. Default is 0. At which position to start the search(item)

Example for indexOf:
Q: Find the first occurrence e here.


var str = "Hello world, welcome to JS";
var n = str.indexOf("e");

alert(n); // 1


Q: Search e which should start position from 5.

var str = "Hello world, welcome to javascript";
var n = str.indexOf("e", 5);

alert(n); // 14


Example for lastIndexOf:


Q: Search last occurrence  "love" from the given string.


var str = "Hello I love JS much.";
var n = str.lastIndexOf("love");
alert(n) // 8

Q: Search item "love" which should start position at 30.


var str = "Hello I love JS very much very much very much";
var find = str.lastIndexOf("very", 30);
alert(find) // 26

Example for includes:


Q: Find 'world' from below given string.


var str = "Hello world, welcome JS.";
var n1 = str.includes("world");

alert(n1); // True

Q: Find 'world' from below given string.


var str = "Hello world, welcome JS.";
var n2 = str.includes("world", 12);

alert(n2); // false










No comments:

Post a Comment