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?
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?
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.
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.find in IE: No, you'd need a polyfill (which is easily come by).null to match, then yes, they need that.