I have a forEach loop where it has a find function inside of it. I'd like to get a boolean value after the forEach is executed only if all the find functions being looped return true. How can this be done?
const items = ['apple','orange','banana'];
items.forEach((item)=>{
const value = !!items?.find((element)=>element==='apple')
console.log(value) // true, false, false -> return of forEach should be false
})
const items = ['apple','apple','apple'];
items.forEach((item)=>{
const value = !!items?.find((element)=>element==='apple')
console.log(value) // true, true, true -> return of forEach should be true
})
Something along the lines of
isAllTruthy = items.forEach((item)=>{
return !!items?.find((element)=>element==='apple')
})
This gives the return value undefined, how do I approach this
You need to take Array#map for the result of the checks. This allowes to return a value for each item of the array.
const
items = ['apple', 'orange', 'banana'],
result = items.map(s => s === 'apple');
console.log(result);
If you like to get a single boolean value, you could use Array#every
console.log(['apple', 'orange', 'banana'].every(s => s === 'apple'));
console.log(['apple', 'apple', 'apple'].every(s => s === 'apple'));
Use .every like this:
const items = ["apple", "orange", "banana"];
let value = items.every((item) => item === "apple");
console.log(value); // false
const items2 = ["apple", "apple", "apple"];
value = items2.every((item) => item === "apple");
console.log(value); // true
You can use only map array method for get return boolean value
const items = ['apple','orange','banana'];
console.log(items.map((e)=> e === 'apple'))