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?

2
  • 2
    The actual code should be posted here, not on jsbin or another site like that. Stack Overflow has all the same facilities. Commented Jul 12, 2020 at 23:36
  • You may check this out: stackoverflow.com/questions/11286950/… Commented Jul 12, 2020 at 23:37

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.