2

I'm currently doing some coursework for university. I am trying to copy an individual value of an old array to a new array, then setting the old arrays value to 0. Obviously if i just assign the value to the new array, then alter the old arrays value, it will overwrite the new array too.

I am not allowed to use the function splice().

here is my code:

function rankedScores(web, pattern) {
    var v = urlScores(web, pattern);
    var sorted = [];
    var maxIndex = 0;
    while (sorted.length < v.length) {
        for (var i = 0; i < v.length; i += 1) {

            if (v[i].score > v[maxIndex].score) {
                maxIndex = i
            }
        }
        sorted[sorted.length] = v[maxIndex];
        v[maxIndex].score = 0;

        maxIndex = 0;
    }
    alert(sorted[0].url + '   ' + sorted[0].score)
    alert(sorted[1].url + '   ' + sorted[1].score)
    alert(sorted[2].url + '   ' + sorted[2].score)
}

If i do this it returns the correct URL value, but all the score values are 0.

Any ideas on how i can stop the arrays from pointing to the same memory location?

Ive tried using a for loop as ive seen this does a shallow copy, but it didnt work

Cheers.

1
  • One option would be to just negate the score and then set it back in a secondary loop. Another to just set the whole array entry to null and to check for that before doing the comparison... Commented Nov 10, 2013 at 15:17

1 Answer 1

1

Replace:

sorted[sorted.length] = v[maxIndex];
v[maxIndex].score = 0;

with:

// ...

var clone = {};
for(var i in v[maxIndex])
    clone[i] = v[maxIndex][i];
sorted[sorted.length] = clone;

v[maxIndex].score = 0;

// ...

Of course, you haven't stated how deep your objects are - I assume they are simple key:value maps but this should be enough to steer you in the right direction.

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

1 Comment

Thank you!! worked a charm. I had tried using a loop to replace the value but i didnt consider using a seperate variable to store the record. Thanks very much!!

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.