Wednesday, April 4, 2018

Array search - find and find Index for an object

Just think, You have an array of objects. How do you find an object with the specific condition in that array?

Here, the arr.find method will do the job for you!

Syntax:

let result = arr.find(function(item, index, array) {
  ..........................
});

item - It is the element.
index  - It is its index.
array  It is the array itself.


Example :


let arr = [

    { name:"string 1", value:"this", other: "that" },

    { name:"string 2", value:"this", other: "that" }

];

let obj = arr.find(o => o.name === 'string 1');

console.log(obj);

Output:
{
  "name": "string 1",
  "value": "this",
  "other": "that"
}

If found happen , returns true and the search will be stopped, the item is returned. If nothing found, undefined is returned.

From the above I have used ES6 arrow function, arr having array of objects. Here o is the parameter (current item) and its getting name from the current and checking with our condition. If its will get match, returns true and further search will be stopped.

If nothing matching undefined will be returned.

Note:
We did not use any other parameter except item , mentioned in the syntax.


arr.findIndex 

               The arr.findIndex method is also same, but it will returns the index where the element was found instead of the element.










No comments:

Post a Comment