Sunday, November 25, 2018

Understanding Array Find() In Javascript

This tutorial explains how to use find() method in array using javascript. The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
  • Find() :- returns the first items in an array that satisfies a condition
Understanding Array Find() In Javascript

Array Reduce() :

Example -1 :
In this example we are filtering the data from the array using find() function, in which we are going to find id value equal 2 from the array object but it is returning only first match from an array. Lets see the below example :
var arr = [
  { id: 1, name: 'Android', score : 20 },
  { id: 2, name: 'Php', score : 10 },
  { id: 3, name: 'React', score : 40 },
  { id: 2, name: 'React Native', score : 30 }
];
const b = arr.find((item) => item.id === 2) 
console.log(b)

Output:-
-----------------------------
> Object { id: 2, name: "Php", score: 10 }


Similarly, we can use reduce() function to find the first match item from an array.

Array Reduce() :

var arr = [
  { id: 1, name: 'Android', score : 20 },
  { id: 2, name: 'Php', score : 10 },
  { id: 3, name: 'React', score : 40 },
  { id: 4, name: 'React Native', score : 30 }
];

const filterdata = arr.reduce((result, item) => {
  if (item.id === 2) { result = item }
  return result
}, null)

console.log(filterdata)

Output:-
-----------------------------
> Object { id: 2, name: "Php", score: 10 }

This is all about Array Find() In Javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment