If entries are being added and removed in an array (not pushed/popped) what is the optimal way to scan and find the first undefined element, so that it can be set with a new value?
6 Answers
If the array contains holes with findIndex you can find the first one like so:
[1, 2,, 4, 5].findIndex(Object.is.bind(null, undefined))
indexOf will ignore holes. So
[1, 2,, 4, 5].indexOf(undefined)
Always returns -1.
1 Comment
undefined values as a content, its not working in this case, using an array created by new Array(4) for example. (tested inside an angular 5 demo app)Assuming we have no prior knowledge of operations being performed on the array, the fastest way is to simply iterate through the entire array linearly
var arr = [1, 2, , 4];
for (var i = 0; i < arr.length; i++) {
if (typeof arr[i] === 'undefined') {
arr[i] = 'foo';
break;
}
}
Or we can keep track of whats being removed using something like this
var earliestRemoved;
if (newRemoved < earliestRemoved || !earliestRemoved) {
earliestRemoved = newRemoved;
}
Comments
I guess the simplest way would be to use Array.indexOf to find the index of the first undefined element.
Today I've got the same question, so here's my take on it.
It all depends on your specific problem. My problem was this:
- I have an array
instances[], with objects in it; - Methods of some of these are registered as callbacks elsewhere;
- Sometimes I do need to remove some instance from an array;
- Sometimes I need to add new instance;
The problem is that I can't just splice an array, because it'll invalidate all my callback registrations. Well, I can just leave them in the array and forget, adding new elements at the end. But it's.... bad. It's leaking memory.
So I came with an idea of making "holes" in an array in place of removed elements, and then re-using these holes for new elements.
Thus the question "how to find undefined elements in an array?".
Someone here suggested using array.indexOf(undefined) - unfortunately that won't work... for some reason.
But, if it's okay in your case to use null or 0 instead, then it will work.
Here's an example:
var A = [1,1,1,1, , ,0,0,null,1,1];
A.indexOf(undefined); // output: -1 (doesn't work)
A.indexOf(0); // output: 6
A.indexOf(null); // output: 8
Hope this'll be useful.
Comments
With the hindsight of about 4.3 years behind me, What I'd do now is, since I'm the owner of the array, is to make an object with 2 arrays in it, the 2nd just contains the indexes that are cleared out. (prob. manage it in a class). So always have clear set with knowledge of what's undefined. This to avoid iterating through arrays linearly.
undefinedduring insert -_- ..then you can liveundefinedfree life