0
function sortproducts(filprodlist)
{
    var prod;
    var k = 0;
    for (i = 0; i < filprodlist.length; i++) {
        var k = i + 1;
        var p=filprodlist[i].EntityKey.substr(filprodlist[i].EntityKey.length - 1);
        var p2=filprodlist[k].EntityKey.substr(filprodlist[k].EntityKey.length - 1);
        if ( p>p2)  {
            temp = filprodlist[k];
            filprodlist[k] = filprodlist[i];
            filprodlist[i] = temp;
        }
    }
    rederProduct(filprodlist);
}

while executing above code getting following error TypeError: filprodlist[k] is undefined

2
  • it's answer is in other part of your code, show it Commented Apr 24, 2014 at 11:10
  • 2
    Why aren't you using the built-in sort method? Commented Apr 24, 2014 at 11:12

3 Answers 3

1

Reason

On last iteration, when i is at last element of array. You are fetching are using var k = i + 1;, where k doesn't exists. Thus you are getting the error.

So Use

for (i = 0; i < filprodlist.length - 1; i++) {

instead of

for (i = 0; i < filprodlist.length; i++) {
Sign up to request clarification or add additional context in comments.

Comments

0

Don't var inside loops, blocks don't have scope in JavaScript, var every variable you want to use in one var statement. End your loop when the highest index reaches the end (k). You can move k into the for's iterate step because you're really iterating with this, too.

function sortproducts(filprodlist) {
    var prod, i, k, p, p2, temp;
    for (i = 0, k = 1; k < filprodlist.length; ++i, ++k) {
        p =  filprodlist[i].EntityKey.substr(filprodlist[i].EntityKey.length - 1);
        p2 = filprodlist[k].EntityKey.substr(filprodlist[k].EntityKey.length - 1);
        if (p > p2)  {
            temp = filprodlist[k];
            filprodlist[k] = filprodlist[i];
            filprodlist[i] = temp;
        }
    }
    rederProduct(filprodlist);
}

A different way to do it is forget k all together, start from i = 1 and use i - 1 and i, this means you're iterating with less variables so it might be easier for you to follow the code in your mind.

Comments

0

Let's say filprodlist has 10 items. Then the items are indexed 0-9 and Your i goes through 0-9. In every iteration You define k = i + 1. So in the last iteration i = 9, k = 10 and You are trying to access filprodlist[10] which doesn't exist (returns undefined). Solution is in @Satpal's answer.

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.