Reputation: 2480
I have an array of objects like this - say testArray.
I need to check that for each object in array, if any of the saveNumbers array is empty, my function should return false.
My function is as follows:
public checkSaveNumbers(): boolean {
let result;
if (this.testArray) {
result = _.some(this.testArray, member => !member.saveNumbers.length);
}
console.log(result);
}
Here, result is showing true for my above object where we can see that the first element in the array has saveNumbers array empty. I'd expect result to be false in that case. I want to achieve this using Lodash and I'm not sure what is going wrong here.
Update:
As suggested in comments, I changed the code to following:
public checkSaveNumbers(): boolean {
let result = true;
if (this.testArray) {
result = _.every(this.testArray, member => member.saveNumbers.length > 0); //as soon as the condition is false, result should become false otherwise result will remain true.
console.log(result);
}
}
However, with this code, even when my saveNumbers array is non-empty for every member in testArray, I get result as false.
Upvotes: 3
Views: 36176
Reputation: 7416
another variant
!_.chain(testArray)
.map('saveNumbers')
.map(_.isEmpty)
.some()
.value()
Upvotes: 1
Reputation: 10762
If any of the saveNumbers array is empty, my function should return false.
You tried:
_.some(array, member => !member.saveNumbers.length)
But this means "true if at least one member has empty saveNumbers." Which is exactly the opposite of what you want.
So negate the entire expression.
!_.some(array, member => !member.saveNumbers.length)
UPDATE:
If this is also not working for you:
_.every(array, member => member.saveNumbers.length > 0)
then you have a bug somewhere else.
Upvotes: 4
Reputation: 10857
You can rewrite your function as follow:
function checkSaveNumber(testArray) {
return !_.some(_.map(testArray, 'saveNumbers'), ['length', 0]);
}
http://jsbin.com/domitexazo/edit?js,console
Upvotes: 2