Bhushan Gadekar Bhushan Gadekar - 2 months ago 6
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 => lib.name === 'Standard');


Now this method checks if any library has a name 'Standard' or not,
it sets
selectedLib
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..:

lib.name=='Standard' ? lib : libraries[0]


Is there a way to do it?

Answer

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 => lib.name === 'Standard') || libraries[0];
console.log(selectedLib);