1

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?

panthro
  • 22,779
  • 66
  • 183
  • 324

1 Answers1

8

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • To elaborate for the OP: `Array.find` just loops through the array and stops when it finds the first element that matches your test -- that is, the first element that makes the callback function return true. As long as your array doesn't have any well-defined order (for instance, alphabetical or numerical or something), the best you can ever do is a linear search, as you don't know what elements comes after which. – IceMetalPunk Nov 20 '18 at 15:01
  • Is it supported in ie? I know no one cares about ie but anyways – Void Spirit Nov 20 '18 at 15:01
  • @Timggwp - Re `find` in IE: No, you'd need a polyfill (which is easily come by). – T.J. Crowder Nov 20 '18 at 15:01
  • you need tho check the value, too: `e => e && typeof e === "object")`. – Nina Scholz Nov 20 '18 at 15:01
  • 1
    @NinaScholz - Depends on what the OP wants. If they don't want `null` to match, then yes, they need that. – T.J. Crowder Nov 20 '18 at 15:02
  • @NinaScholz i think the answer given fully satisfies the question since `null`'s type is `object` :) – Void Spirit Nov 20 '18 at 15:05
  • 1
    @Timggwp - :-) Nevertheless, it's a good point I added to the answer and probably should have mentioned before she brought it up. – T.J. Crowder Nov 20 '18 at 15:13