Have you ever come across a requirement to find a particular object in a given array of objects? In this post, we will explore various ways to find a particular object in a JavaScript array. Let us assume that we have an array as shown in the listing below and we need to find whether an object with an Id of ‘4’ exists:
var tasks = [ { 'Id':'1', 'Title':'Go to Market 99', 'Status':'done' }, { 'Id':'2', 'Title':'Email to manager', 'Status':'pending' }, { 'Id':'3', 'Title':'Push code to GitHub', 'Status':'done' }, { 'Id':'4', 'Title':'Go for running', 'Status':'done' }, { 'Id':'5', 'Title':'Go to movie', 'Status':'pending' }, ];
To search a particular object, we will use the Array prototype find method. This returns a value on a given criterion, otherwise it returns ‘undefined’. It takes two parameters, one required callback function and an optional object, which will be set as value of this inside the callback function.
- The callback function will be called for each element of the array until the given condition for a particular element is not true.
- An object which will be the value of this in the callback function is an optional parameter, and if it’s not passed, the value will be set to undefined in the callback function.
The callback function parameter of the find method takes three parameters:
- element: the current element being processed in the array
- index: the index of the current element being processed
- array: the array on which the find method is being called
Let us say we have a callback function as shown in the listing below. It will print the current element, index of the element, and the array:
function CallbackFunctionToFindTaskById(element, index, array) { console.log(element);// print element being processed console.log(index); // print index of the element being processed console.log(array); // print the array on which find method is called }
How does the find method work?
- The JavaScript find method will execute the callback function for each element of the array. So if there are 5 elements in the array, the callback function would be executed five times.
- The JavaScript find method will break the execution of the callback function when it finds a true criterion for a particular element.
- If the given criterion is true for an element, the JavaScript find method will return that particular element, and will not execute the callback function for the remaining elements.
- If the criteria are not true for any elements, the JavaScript find method will return undefined.
- The JavaScript find method does not execute the callback function for indexes which are either not set or have been deleted.
- The JavaScript find method always executes the callback function with three arguments: element, index, array.
Let us see some examples of using the find method!
Find an object on a fixed criterion
We have a tasks array as shown in the listing below:
var tasks = [ { 'Id':'1', 'Title':'Go to Market 99', 'Status':'done' }, { 'Id':'2', 'Title':'Email to manager', 'Status':'pending' }, { 'Id':'3', 'Title':'Push code to GitHub', 'Status':'done' }, { 'Id':'4', 'Title':'Go for running', 'Status':'done' }, { 'Id':'5', 'Title':'Go to movie', 'Status':'pending' }, ];
We want to find an object with an Id of ‘4’. We can do that as shown in the listing below:
function CallbackFunctionToFindTaskById(task) {return task.Id ==='4'; }var task = tasks.find(CallbackFunctionToFindTaskById); console.log(JSON.stringify(task));
In the above listing, we are passing the callback function CallbackFunctionToFindTaskById in the find method of tasks array. Always first parameter of the callback function represents element parameter. Here task is representing element inside the callback function. So, task represents the element currently being processed.
In the callback function, we are checking the Id of the current task and if it is equal to 4, returning the task. In this scenario criteria is fixed inside the callback function.
Find an object on criteria passed in the callback function
In the previous example, we had a fixed criterion that returned any object with the Id of ‘4’. However, there could be a requirement in which we may want to pass the criteria while calling the callback function. We can pass an object as the value of this in the callback function. Let us consider the same tasks array again, which is shown in the listing next
var tasks = [ { 'Id':'1', 'Title':'Go to Market 99', 'Status':'done' }, { 'Id':'2', 'Title':'Email to manager', 'Status':'pending' }, { 'Id':'3', 'Title':'Push code to GitHub', 'Status':'done' }, { 'Id':'4', 'Title':'Go for running', 'Status':'done' }, { 'Id':'5', 'Title':'Go to movie', 'Status':'pending' }, ];
Next let us create a callback function FindTaskById as shown in the listing below:
function FindTaskById(task) { console.log(this); }
As you notice we are printing the value of “this” inside the callback function. Next we’ll pass the FindByTask callback function in the find method of tasks array as shown in the listing below:
var task = tasks.find(FindTaskById,['4','67']);
In this case, the value of this inside callback function has been set to an object with two values: 4 and 67. In the console, you should get the output as shown below:
The value of this is printed 5 times because there are 5 elements in the tasks array. To return an object with the Id set to 4, we need to modify the callback function as shown in the listing below
function FindTaskById(task) {if (task.Id ===this[0]) {return task; } }var task = tasks.find(FindTaskById, ['4', '67']); console.log(JSON.stringify(task));
In the callback function, we are passing the value of this object with the first property set to 4. Hence checking whether the task.Id is equal to this[0] or not will return an object with Id 4.
Conclusion
In this post, we learned about the JavaScript Array find method and various options with the callback function. Having a better understanding of the find method is essential to be a more productive JavaScript developer and I hope you enjoyed reading!