clever_bassi clever_bassi - 5 days ago 8
AngularJS Question

Lodash - Check for empty array in an array of objects using _.some

I have an array of objects like this - say testArray.
enter image description here
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.

Answer

You can rewrite your function as follow:

function checkSaveNumber(testArray) {
    return !_.some(_.map(testArray, 'saveNumbers'), ['length', 0]);  
}

http://jsbin.com/domitexazo/edit?js,console