DEV Community

loading...

Array.find Method in JavaScript

askavy profile image Avnish Jayaswal Originally published at askavy.com ・1 min read

The JavaScript Array find method is a way to find and return the first occurrence of an element in an array , Array.find only return a single matched element , if nothing is find then it return undefined

  var array = ['cat', 'dog' , 'car']; 


  var found = array.find(function (element) { 
      return element == 'dog'; 
  }); 


  document.write(found);  // return dog
Enter fullscreen mode Exit fullscreen mode

        var array = [10, 20, 30, 40];

        var found = array.find(function (element) {
            return element > 10;  
        });

        document.write(found);  // return 20

Enter fullscreen mode Exit fullscreen mode

Array find with startsWith javascript function


    const vehicles = [
        "car",
        "bus",
        "truck",
        "SUV"
    ];

    const result = vehicles.find(tree => tree.startsWith("c"));

    document.write(result) ;  // car

Enter fullscreen mode Exit fullscreen mode

Array Find using JavaScript object


            const vehicles = [
                { name: "car", count: 4 },
                { name: "bus", count: 5 },
                { name: "SUV", count: 2 }
            ];


            const result = vehicles.find(vehicle => vehicle.name == 'SUV');

            console.log(result);  // {name: "SUV", count: 2}

Enter fullscreen mode Exit fullscreen mode

Array Find on a JavaScript object with index i

                const vehicles = [
                    { name: "car", count: 4 },
                    { name: "bus", count: 5 },
                    { name: "SUV", count: 2 }
                ];

                const result = vehicles.find((vehicle, i) => {
                    if (vehicle.count > 1 && i !== 0) return true;
                });

                console.log(result);  // {name: "bus", count: 5}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide