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.

0

3 Answers 3

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);

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

Comments

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);

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.