9

If I have an array like [{a:'b'},{}] and if I try to find an index of element {}. Then I am unable to get the correct index.

I have tried indexOf,findIndex and lodash's findIndex but all is returning -1 instead of 1 maybe because of reference.

The actual index should be 1 instead of -1.

3 Answers3

6

You can make use of findIndex and Object.keys():

const arr = [{a:'b'}, {}];

const emptyIndex = arr.findIndex((obj) => Object.keys(obj).length === 0);

console.log(emptyIndex);
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
2

If you search for an empty object, you search for the same object reference of the target object.

You could search for an object without keys instead.

var array = [{ a: 'b' }, {}] ,
    index = array.findIndex(o => !Object.keys(o).length);

console.log(index);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can use Object.keys(obj).length === 0 && obj.constructor === Object for check empty object.

var a = [{a:'b'},{}] 
    var index;
    a.some(function (obj, i) {
        return Object.keys(obj).length === 0 && obj.constructor === Object ? (index = i, true) : false;
    });
    console.log(index);

var a = [{a:'b'},{}] 
var index;
a.some(function (obj, i) {
    return Object.keys(obj).length === 0 && obj.constructor === Object ? (index = i, true) : false;
});
console.log(index);
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62