1const inventory = [
2 {name: 'apples', quantity: 2},
3 {name: 'cherries', quantity: 8}
4 {name: 'bananas', quantity: 0},
5 {name: 'cherries', quantity: 5}
6 {name: 'cherries', quantity: 15}
7
8];
9
10const result = inventory.find( ({ name }) => name === 'cherries' );
11
12console.log(result) // { name: 'cherries', quantity: 5 }
1// Use array.find() like this:
2
3var myArrayOfAges = [1,4,6,8,9,13,16,21,53,78];
4
5var result = myArrayOfAges.find(age => age >= 12);
6
7console.log(result); // Output: 13
8
9/* ------ Below is a polyfill from Mozilla: ------ */
10
11// https://tc39.github.io/ecma262/#sec-array.prototype.find
12if (!Array.prototype.find) {
13 Object.defineProperty(Array.prototype, 'find', {
14 value: function(predicate) {
15 // 1. Let O be ? ToObject(this value).
16 if (this == null) {
17 throw TypeError('"this" is null or not defined');
18 }
19
20 var o = Object(this);
21
22 // 2. Let len be ? ToLength(? Get(O, "length")).
23 var len = o.length >>> 0;
24
25 // 3. If IsCallable(predicate) is false, throw a TypeError exception.
26 if (typeof predicate !== 'function') {
27 throw TypeError('predicate must be a function');
28 }
29
30 // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
31 var thisArg = arguments[1];
32
33 // 5. Let k be 0.
34 var k = 0;
35
36 // 6. Repeat, while k < len
37 while (k < len) {
38 // a. Let Pk be ! ToString(k).
39 // b. Let kValue be ? Get(O, Pk).
40 // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
41 // d. If testResult is true, return kValue.
42 var kValue = o[k];
43 if (predicate.call(thisArg, kValue, k, o)) {
44 return kValue;
45 }
46 // e. Increase k by 1.
47 k++;
48 }
49
50 // 7. Return undefined.
51 return undefined;
52 },
53 configurable: true,
54 writable: true
55 });
56}
1const list = [5, 12, 8, 130, 44];
2// a find metóduson belül a number egy paraméter
3// azért nem szükséges köré a zárójel, mert csak egy paramétert adunk át
4// minden más esetben így kell írni:
5// const found = list.find((index, number) => number > index);
6const found = list.find(number => number > 10);
7console.log(found);
8// --> 12