Here's some code that runs each value in the array against an expensiveOperation
function, and returns the first one that meets some criteria.
let result = [1, 2, 3, 4, 5].find(value => {
let newValue = expensiveOperation(value)
return meetsCritera(newValue)
}
result = expensiveOperation(result)
But what's returned from the find
function is the array value (e.g. 3
), rather than the result of expensiveOperation(3)
. To get that final value, I need to run expensiveOperation
once more outside the body of find
.
How can I avoid running it once more and return the desired value from find
. Is there another ES6 array function that would let me do this?
Here's some code that runs each value in the array against an expensiveOperation
function, and returns the first one that meets some criteria.
let result = [1, 2, 3, 4, 5].find(value => {
let newValue = expensiveOperation(value)
return meetsCritera(newValue)
}
result = expensiveOperation(result)
But what's returned from the find
function is the array value (e.g. 3
), rather than the result of expensiveOperation(3)
. To get that final value, I need to run expensiveOperation
once more outside the body of find
.
How can I avoid running it once more and return the desired value from find
. Is there another ES6 array function that would let me do this?
- your just returning the condition true or false not the value – Roljhon Commented Jan 20, 2017 at 19:29
- 1 assign the value to a variable which has scope outside the function.... – Pranav C Balan Commented Jan 20, 2017 at 19:36
3 Answers
Reset to default 4You can always use a good old loop:
let result;
for (let value of [1, 2, 3, 4, 5]) {
let newValue = expensiveOperation(value);
if (meetsCritera(newValue)) {
result = newValue;
break;
}
}
You could use Array#some
and exit the loop if the criteria is met.
var expensiveOperation = a => 3 * a,
meetsCritera = v => v > 10,
result = (() => {
var newValue;
return [1, 2, 3, 4, 5].some(value => {
newValue = expensiveOperation(value);
return meetsCritera(newValue);
}) && newValue;
})();
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This is a decent usecase for .reduce
.
let result = [1, 2, 3, 4, 5].reduce((result, value) => {
if (result) return result;
let newValue = expensiveOperation(value)
if (meetsCritera(newValue)) return newValue;
}, null);