panthro
panthro

Reputation: 24099

Find an object in an array?

I have an array:

['test', 'test2', {a: a, b: b}, 'test3']

How can I get the first object only?

Would I need to loop through and do a type test? Or is there a more efficient way?

Upvotes: 1

Views: 71

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075587

Would I need to loop through and do a type test?

You do, or at least, something does.

For instance, to find the first object in the array, you could use find:

const first = theArray.find(e => typeof e === "object");

Or if you don't want null to match:

const first = theArray.find(e => e && typeof e === "object");

Or is there a more efficient way?

Looping's going to be sufficiently efficient. If you don't like the calls to find's callback (they're really, really, really fast), you could use a boring old for loop:

let first;
for (let i = 0, l = theArray.length; i < l; ++i) {
    const e = theArray[i];
    if (typeof e === "object") { // Or, again: `e && typeof e === "object"`
        first = e;
        break;
    }
}

...but the odds that it makes a performance difference you can actually perceive are vanishingly small.

Upvotes: 8

Related Questions