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?

2
  • Possible duplicate of Get first element in array Commented Nov 20, 2018 at 14:59
  • No, he means how do you find the first item of the array of type object Commented Nov 20, 2018 at 15:00

1 Answer 1

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.

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

7 Comments

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.
Is it supported in ie? I know no one cares about ie but anyways
@Timggwp - Re find in IE: No, you'd need a polyfill (which is easily come by).
@NinaScholz - Depends on what the OP wants. If they don't want null to match, then yes, they need that.
@Timggwp - :-) Nevertheless, it's a good point I added to the answer and probably should have mentioned before she brought it up.
|

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.