0

I am doing this challenge on leetcode.

Why is it that, this answer is accepted?

My Code:

/**
 * @param {number[]} nums
 * @return {string[]}
 */
var findRelativeRanks = function(nums) {
    const map = new Map();
    let result;
    nums
        .slice()
        .sort((a, b) => b - a)
        .forEach((num, i) => map.set(num, (i + 1).toString()));
    result = nums.map(num => {
        switch(map.get(num)) {
            case "1":
                return "Gold Medal";
            case "2":
                return "Silver Medal";
            case "3":
                return "Bronze Medal";
            default:
                return map.get(num);
        }
    })
    return result;
};

But if I just remove .slice(), some test cases fail. Why?

smmehrab
  • 756
  • 9
  • 16
William
  • 61
  • 1
  • 6
  • 2
    The actual code should be posted **here**, not on jsbin or another site like that. Stack Overflow has all the same facilities. – Pointy Jul 12 '20 at 23:36
  • You may check this out: https://stackoverflow.com/questions/11286950/using-the-javascript-slice-method-with-no-arguments – smmehrab Jul 12 '20 at 23:37

1 Answers1

2

Slice returns a shallow copy of the array.

nums.slice().sort(/* ... */).forEach()

will

  1. copy the array with slice
  2. sort the array
  3. iterated the sorted, copied array.

However, further accesses to 'nums' will not be sorted because the copy was not saved anywehre.

Rubydesic
  • 3,386
  • 12
  • 27