Bhushan Gadekar Bhushan Gadekar - 20 days ago 4x
Javascript Question

How to call a method if array.find() does not return anything?

I am searching for element in array using array.find() like below:

this.selectedLib = libraries.find(lib => === 'Standard');

Now this method checks if any library has a name 'Standard' or not,
it sets
as Standard if it has 'Standard'.

But if there is no library with name Standard , I want to set library at index position 0 to be selectedLib.

something like this..:'Standard' ? lib : libraries[0]

Is there a way to do it?


The find() method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned


var libraries = [{
  name: "Not Standard",
  id: 1
}, {
  name: "Not Standard",
  id: 2
var selectedLib = libraries.find(lib => === 'Standard') || libraries[0];