Home > database >  In javascript find () method of an array how to get any element using only array argument of the cal
In javascript find () method of an array how to get any element using only array argument of the cal

Time:11-14

var check = [1,2,3,4,5,6]; var check1 =check.find((elements,index,array)=>{ return array ;}); console.log(check1); // output : 1. Why? And if i want 3 as output from above array by giving checks or condition to the array argument then how to get it?//

CodePudding user response:

The find method executes the callbackFn function once for each index of the array until the callbackFn returns a truthy value. If so, find immediately returns the value of that element. Otherwise, find returns undefined.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

And since you aren't really doing any checks and just returning c (a truthy value), which is the array itself, that's why it returns 1.

If you want to find 3 or any other value, you do the following (also name your function params better so it's easier to understand what is going on):

var check = [1, 2, 3, 4, 5, 6];
var check3 = check.find((element, index, array) => {
  return element === 3
});
console.log(check3); // output : 3

CodePudding user response:

In response to OP request in comments. The third parameter of the callback function passed into array.find can be used to modify the original array based on a condition. This example switches even values to the odd value 1.

const check = [1,2,3,4,5,6]
check.find((el, index, arr) => {
    if (el % 2 === 0){
        arr[index] = 1
    }
})
console.log(check) // [2,2,3,4,5,6]

However, this is not the proper use of .find, and .find should not be used in this way. .find should be used to simply return the first value of an array that satisfies a condition, as decho explained in his answer. If you are wanting to update the values in an array consider using a for loop or .forEach.

CodePudding user response:

Based on your comment here's how to check if a number exists at a particular index, and returning the number based on that check.

var check = [1, 2, 3, 4, 5, 6];

var check1 = check.find((el, i, arr) => {
  return arr.indexOf(3) > 1 && el === 3;
});

var check2 = check.find((el, i, arr) => {
  return arr.indexOf(3) > 3 && el === 3;
});

console.log(check1);
console.log(check2);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related