0

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

3
  • is there a reason not to just implement a custom sort using the property value? i.e. 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. Commented Oct 7, 2014 at 0:39
  • Well couldn't figure out why my method wouldn't work, but instead of inserting in order I ended up just using the native Array.sort at the end that compared a.SetIndex and b.SetIndex EDIT: I wrote this at the same time intothev01d answered, that is what I ended up doing. But if anyone knows why the original didn't work it would be appreciated Commented Oct 7, 2014 at 0:40
  • You're missing a for( var i=0; i<…! Commented Oct 7, 2014 at 1:14

1 Answer 1

1

You have:

for (i = 0; i < this.length; i++) {
    if(i+1 > this.length)
    {
         // dead code

the maximum of i (inside the loop) is this.length-1. Therefore, (i+1 > this.length) can never be true.

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

Comments

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.