Search code examples
javascriptarraysshallow-copy

Copying element of existing array to a a new array without using splice?


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.


Solution

  • 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.