Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 257
clever_bassi Avatar asked Jun 29 '26 01:06

clever_bassi


2 Answers

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.

like image 66
lawrence Avatar answered Jul 01 '26 15:07

lawrence


You can rewrite your function as follow:

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

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

like image 36
Kevin Le - Khnle Avatar answered Jul 01 '26 14:07

Kevin Le - Khnle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!