//find method returns the first element in an array which meets
// a condition
let numbers = [-1,-2,-4,-6,0,1,2,3,4,5];
const greaterThanZero = (val) => val > 0;
numbers.find(greaterThanZero);
//Expected output
//1
//filter returns an array of elements that meet a condition
numbers.filter(greaterThanZero);
//Exected output
//[1,2,3,4,5]
both usually work: the format is identical
find gets the first value that matches your criteria
filter gets all the values in the array that matches your criteria
Example
let dates = ["2022-10-17", "2022-10-18"];
for(var i in dates)
{ customDatesStyles.push({
startDate: moment(dates[i])
});
}
function change(da)
{ console.log(customDatesStyles[0].startDate);
console.log(da);
let d = customDatesStyles.find((el)=> el.startDate.format("YYYY-MM-DD") == da.format("YYYY-MM-DD")));
}
both filter and find would have been fine.
The answer with filter would just have needed to be d[0] (although there is only one in this case).
But filter can have more than one case, whereas find stops at the first found case.
find() vs filter() in JavaScript – Differences Explained with Examples
/* The main differences between above examples is:
filter() returns an array containing the element that satisfies the condition,
but find() returns the element itself that satisfies the condition.
In filter(), whole array is iterated despite the fact that the element being
searched for is present at the beginning.
But in find(), as soon as the element that satisfies the condition is found,
it gets returned.
*/
find() vs filter() in JavaScript – Differences Explained with Examples
/* What is the filter() method?
This method returns all the elements of the array that satisfy the condition
specified in the callback function.
*/
const x = [1, 2, 3, 4, 5];
const y = x.filter(el => el*2 === 2);
console.log("y is: ", y); // y is: [1]
/* If you check out the output of the above example,
the value of y is an array of 1 element that satisfies the condition.
This is because the filter() method iterates over all elements of the array and
then returns a filtered array which satisfy the condition specified.
*/
/* What is the find() method?
This method returns first element of the array that satisfies the condition
specified in the callback function.
*/
const x = [1, 2, 3, 4, 5];
const y = x.find(el => el*2 === 2);
console.log("y is: ", y); // y is: 1
/* Now, if you see the output of the above example, the value of y is 1.
This is because the find() method searches for first element in the array
that satisfies the condition specified.
*/
/* The main differences between above examples is:
filter() returns an array containing the element that satisfies the condition,
but find() returns the element itself that satisfies the condition.
In filter(), whole array is iterated despite the fact that the element being
searched for is present at the beginning.
But in find(), as soon as the element that satisfies the condition is found,
it gets returned.
*/