Most Used JavaScript Array Methods – Finding The Elements

Most Used JavaScript Array Methods – Finding The Elements

Share this post

Most Used Array Methods for Finding the Elements

Hello everyone. We bring the most used JavaScript Array methods. First talk about the Javascript Challenge#2, which I asked you in our previous lesson on JavaScript Array Methods for Add and Remove. If you didn’t read, click on the link below and read it, so you will have a good idea about other important JavaScript arrays methods.

“JavaScript Array Methods – Add and Remove Elements”

Solution for JavaScript Challenge#2 as below,

var prime = [2, 3, 5, 7, 11, 13, 17, 19, 23];

var prime10 = prime.slice(4, 8);

OR

var prime10 = prime.slice(4, -1);

console.log(prime10);   // [ 11, 13, 17, 19 ]

Let’s start today’s lesson. Today we will discuss, mostly used javaScript methods which are very useful when we work with Arrays.

includes / indexOf / lastIndexOf

All of these javaScript array methods are quite similar in nature and syntax. These methods search a given value in the list of array elements and return one value on the basis of their search result. All of them take 2 parameters,

First Parameter: the value you want to search in the array. It is case sensitive.

Second Parameter (Optional): This is the index number from where you want to start the search. This can be negative also. This is an optional parameter, so if you do not give the second parameter, It will take 0 by default and start searching from the very first element.

As the second parameter is optional, let’s first discuss all three methods only with the first parameter and later discuss the second parameter collectively.

includes

This method will search the given value in the array elements and if found, it returns the result true or returns false if not found. Its syntax

array.includes(value to search, index number from where to search(Optional));
 //expected result true or false

Let’s see the examples

var games = [  'football',  'basketball',  'cricket',  
'hockey',  'tennis',  'golf',  'baseball', 'basketball'];

var have = games.inclueds('tennis');

console.log(have);    // true

var notHave = games.inclueds('rugby');

console.log(notHave);   //false
indexOf

Same as the method include(), indexOf() searches a given value in the array elements, and return the index number of the first matched element or return -1 if not found the value in the array. Its syntax

array.indexOf(value to search, index number from where to search(Optional));
 //expected result indexNumber or -1

Let’s see the examples

var games = [  'football',  'basketball',  'cricket',   'hockey',  
                                     'tennis',  'golf',  'baseball', 'basketball'];

var have = games.indexOf('tennis');

console.log(have);    // 4

var notHave = games.indexOf('rugby');

console.log(notHave);  //-1
lastIndexOf

Same as the method index(), lastIndexOf() also searches a given value in the array elements and returns the index number but instead of the first matched element, it gives the index of last matched element. It returns -1 if no element found for searched value in the array. Its syntax

array.indexOf(value to search, index number from where to search(Optional));
 //expected result indexNumber or -1

Let’s see the examples

var games = [  'football',  'basketball',  'cricket',   'hockey',  
                                     'tennis',  'golf',  'baseball', 'basketball'];

var have = games.lastIndexOf('basketball');

console.log(have);    // 7

var notHave = games.indexOf('rugby');

console.log(notHave);  //-1
The second parameter in includes, indexOf, and lastIndexOf

Let’s now discuss the second parameter, index number from where we want to start to search. By, default this parameter is considered 0, so the search starts from the first element of the array. In includes() and indexOf(), the search starts from the provide index number and in the forward direction. But in lastIndexOf(), the search starts from index number but in backward direction means from last to the first element.

Let see it with the help of an example

games array javaScript array tutorials

var games = [  'football',  'basketball',  'cricket',   'hockey',  
                                        'tennis',  'golf',  'baseball', 'basketball'];

var gameIncludes = games.includes('cricket', 1);
var gameIndexOf = games.indexOf('cricket', 1);
var gameLastIndexOf = games.lastIndexOf('basketball', 3);
console.log(gameIncludes);      // true
console.log(gameIndexOf);      // 2   (it started from index 1 in forward direction)
console.log(gameLastIndexOf);  // 1   (it started from index 3 in backward direction)

For index 0, 1, and 2, “gameIncludes” is true as cricket at index 2 (which is gameIndexOf). After index 2, such as 3,4, and so on, “gameIncludes” will be false and gameIndexOf” will be -1, because, in the array games, we don’t have any other cricket.

lastIndexOf() methods work in the backward direction therefore when we used from index 3 it only counts first basketball which is at index 1. if I try index 0, it will return -1 which means not found.

var gameIncludes = games.includes('cricket', -6);
var gameIndexOf = games.indexOf('cricket', -6);
var gameLastIndexOf = games.lastIndexOf('basketball', -3);

console.log(gameInclude);      // true
console.log(gameIndexOf);      // 2   (it started from index 8+(-6)=2 in forward direction)
console.log(gameLastIndexOf);  // 1   (it started from index 8+(-3)=5 in backward direction)

For negative index, array.length + negative index = positive index. Means if our array length is 8 and negative array is -6 then it will be 8+(-6) = 2. So, it will follow the same rule as a positive index example, for any negative number less than 5 like -6,-7, and so on, “gameInclude” will be true as cricket at index 2 ( which is gameIndexOf)

gameLastIndexOf also behaves the same as others like 8+(-3)=5. So, It will follow the same rule as the positive index example. It starts searching from index number 5 in the backward direction and find basketball at index 1.

filter / find / findIndex / some

These JavaScript array methods are quite similar in nature and syntax except one thing as filter() array method returns a separate array with all matched results as an element and find(), findIndex(), and some() return only first matched result. These methods checked a condition in the parent array elements and return the result on the basis of their search. All of them take 2 parameters,

First Parameter: callback function which sets the search condition. this function takes 3 arguments

  1. current element of the parent array which is going to be processed
  2. index number (Optional) of the current element.
  3. array (Optional) the parent array itself on which method going to be processed

Second Parameter (Optional): It is the “this” argument that can be used while performing the callback function. This is also an optional parameter. This parameter to use when we want to use the callback function value at the same time. By default it is undefined.

filter

This method gives a new array with all the elements, from its parent array, who meet with a given condition. Let’s see with the example

var games = [  'football',  'basketball',  'cricket',  
                   'hockey',  'tennis',  'golf',  'baseball', 'basketball'];

var game = games.filter((e) => e.includes('ball'));

console.log(games2);    //[ 'football', 'basketball', 'baseball', 'basketball']

game = games.filter((e) => e.length <= 6);

console.log(games3);   //[ 'hockey', 'tennis', 'golf' ]

In the above examples, we called a callback function e=>e.includes(‘ball’). This function will test all the elements in the parent array game and if the result comes true, that element inserted into a new array games2.

This function does check all the elements in the parent array. What if we want to check only the first element who meet the given condition or just wants to check the array has any particular element. For this we have another method find.

find

Unlike the filter method, find() method do not return a new array. It just returns the first element which met the condition in the callback function but if no element matches the condition, it returns undefined. Let’s see with the help of games array

var games = [ 'football',  'basketball',  'cricket',  
                             'hockey',  'tennis',  'golf',  'baseball', 'basketball'];

var game = games.find(e => e.includes('ball'));

console.log(game);      // football

game = games.find(e => e.includes('rugby'));

console.log(game);     // undefined

To get the index number of the element who meets the condition we have another method for that.

findIndex

This method is the same as find() method, the only difference is, it gives the index number of the first element found who meets the condition but if not found and match then it returns -1. Let’s see the example

var game = games.findIndex(e => e.includes('golf'));

console.log(game);          // 5

game = games.find(e => e.includes('rugby'));

console.log(game); // -1
some

This method also the same as find, the only difference is it returns Boolean output true or false. It finds the first element where given condition match if it matched it returns true else returns false. Let’s see the example

var game = games.findIndex(e => e.includes('golf'));

console.log(game);          // true

game = games.find(e => e.includes('rugby'));

console.log(game);         // false

These are some very useful JavaScript Array methods about Finding the elements. If you have any questions regarding this topic or any other javaScript topics please mention in the comment, so that I can promptly reply to you. And if you have not read our previous lessons of JavaScript Array, just click the link below and read it.

JavaScript Tutorial lessons

you can also visit MDN website for more details.

JavaScript Challenge#3

Now, time for yet another javaScript challenge for you. I want a new array from the below array “numbers” with all the odd numbers only. The new array name will be “oddNumbers”. Use any of the methods I explained in this lesson above, which suits best for this challenge. Write your answers in the comment box. I will reply to you there, Let’s see who will be correct. Also if you can’t get the answer, don’t worry as you can check the answer in our coming lesson about the Array methods, I will provide the link soon.

var numbers= [2,5,97,58,48,36,45,79,63,59,5,22,60];

We will come again with some more knowledge very soon. Sign up with us so that you will not miss any of the future articles in the sequence of JavaScript tutorials. You can also follow us on our twitter or Facebook pages for all the future Lessons.

If you’re interested, Check out some other articles related to present crisis Coronavirus

Take care of yourself and your family!♥

Leave a Comment

Your email address will not be published. Required fields are marked *