Been working with this simple task for a bit now and I just can't seem to figure out what the issue is. I have an array of objects, each object has a SetIndex property and I want to insert objects and maintain the array ordered by the objects Set Indices. I thought this was fairly simple but it does not seem to be working as I had expected.
The native method inserts, but the chunk that checks if the array is empty always seems to evaluate to true, and overwrites index 0 every time and does not execute the splice. I think it is something simple about JS I am missing, but I can't seem to figure it out.
Array.prototype.insertAtIndex = function(item) {
for (i = 0; i < this.length; i++) {
if(i+1 > this.length)
{
if(this[i].SetIndex <= item.SetIndex && this[i+1].SetIndex >= item.SetIndex)
{
this.splice(i,0,item);
}
}
}
if(this[0].length == 0);
{
this[0] = item;
}
};
I run the following to test the function
item1 = {SetIndex: 0,name: 'item1'};
item2 = {SetIndex: 1,name: 'item2'};
item3 = {SetIndex: 2, name: 'item3'};
item4 = {SetIndex: 3, name: 'item4'};
item5 = {SetIndex: 4, name: 'item5'};
console.log(item1.SetIndex);
my_array = [];
my_array.insertAtIndex(item2);
console.log(my_array);
my_array.insertAtIndex(item1);
console.log(my_array);
my_array.insertAtIndex(item5);
I have tried using if(this[0] == undefined) as well to check if the array is empty but nothing works as I planned
my_array.sort(function(a, b) { return a.SetIndex - b.SetIndex; });you can sort it whenever you need to make sure they stay in order this way if you need.for(vari=0; i<…!