0

I am trying to check if the length of array 1 matches the length of array 2, and that array 1 does not contain empty objects

my attempt

const matrixValues = _.size(array1,Object.keys(array1.map(item => item)).length !== 0) === array2.length

array2: [{'somevalue': '1'}, {'somethingelse: '2'}, {'somethingmore': '3'}]

array1: [ {'somevalue': '1'}, {'somethingelse': '2'}, {} ] array1 has a length of 3 here, but it contains an empty object, so we should return false, the empty object check should also not rely on the index of the element

2
  • you forget negative index elements, which are not taken into account by Array.length Commented Aug 25, 2020 at 0:12
  • @MisterJojo - Negative index items are not array elements. They are just properties on the object. Same as items indexed by a non-numeric string. Commented Aug 25, 2020 at 0:28

1 Answer 1

3

Compare the length of both arrays and for the first one use Array#every to look if there is for every object at least one property (so it is not empty).

Extended: Same test if I delete in the first array (array3 in example) all empty objects can be done with Array#filter.

let array2 =  [{'somevalue': '1'}, {'somethingelse': '2'}, {'somethingmore': '3'}];
let array1 = [ {'somevalue': '1'}, {'somethingelse': '2'}, {} ];
let array3 =  [{'somevalue': '1'}, {}, {'somethingelse': '2'}, {}, {'somethingmore': '3'}];

let result = (array1.length===array2.length) &&
    array1.every(obj => Object.keys(obj).length);
console.log('Same length without delete empty objects:', result);

let result2 = (array3.filter(obj => Object.keys(obj).length).length === array2.length);
console.log('Same length with delete empty objects:',result2);

Sign up to request clarification or add additional context in comments.

2 Comments

OP might also want to consider if filtering out empty objects that makes array lengths the same is valid
I extended it to your wishes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.