Array find()
The find () method searches for the specified value in the array. Returns the first providing value.
Syntax:
array.find(function(element))
element( Required ): It is the element of the array on which array.find() function works.
Return value: It return returns the array element value if any of the elements in the array which satisfy the condition, otherwise it returns undefined.
let list = [5, 12, 42, 64, 9];
var control = list.find(function (x) {
return x > 20;
});
console.log(control);
output:
42
If a element parameter is provided to find, it will be used as the this for each invocation of the callback. If it is not provided, then undefined is used.
let list = [1, 2, 3, 4, 5];
var control = list.find(function (x) {
return;
})
console.log(control)
output:
undefined
Examples
Example-1 (age control)
let ages = [12, 16, 22, 34, 56];
var ageControl = ages.find(function (x) {
return x >= 18;
})
console.log(ageControl)
output:
22
Example-2 (quantity rotation)
// html codes:
<input type="text" id="val" />
<input type="button" id="find" value="Find"/>
//javascirpt codes:
<script>
find = document.getElementById("find")
find.onclick = function () {
let things = [
{ name: "pencil", quantity: 12 },
{ name: "eraser", quantity: 7 },
{ name: "book", quantity: 3 },
{ name: "scissors", quantity: 10 }
];
var variable = document.getElementById("val").value;
var result = things.find( x => x.name === variable);
console.log(result)
}
</script>

output:
name: “pencil”, quantity: 12

output:
name: “eraser”, quantity: 7
Polyfill
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
value: function(predicate) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var thisArg = arguments[1];
while (k < len) {
if (predicate.call(thisArg, kValue, k, o)) {
return kValue;
}
}
return undefined;
},
configurable: true,
writable: true
});
}
Browser Support
Chrome | 45 |
Edge | Yes |
Firefox | 25 |
Internet Explorer | No |
Opera | 32 |
Safari | 8 |
Android webview | Yes |
Chrome for Android | Yes |
Edge mobile | Yes |
Firefox for Android | 4 |
Opera Android | Yes |
iOS Safari | 8 |
Advertisements
3 Comments »