0

The whiteboard problem is: find shortest string in an array and then shorten all of the other strings to that length starting at index 0

I use sorting to find the shortest string. (not best practice but hey i'm learning). But when I try to map the arr later, it remains sorted, even if I set it to a different variable early in the function. Is this an issue with let? should I be using const instead?

my unsorted.map is returning a sorted array. I have no idea why.

Here is my solution:

function cutIt(arr){
    let unsorted = arr;
    console.log(unsorted)
    
    let sortedArr = arr.sort((a, b) => a.length - b.length);
    let shortest = sortedArr[0].length;
    
    console.log(unsorted)
    
    return unsorted.map(str => str.slice(0, shortest))
}
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
tryingCode
  • 11
  • 7
  • You can look at ways of cloning the array before sorting it. But perhaps easier would be to `map` over it to get the lengths of the strings, and call `Math.min(...lengths)` to get your `shortest` value, and proceed with your final `map`. – Scott Sauyet Jun 24 '20 at 16:23
  • @ibrahimmahrir: The answer there will solve the problem, yes, but there are better solutions to the underlying problem. – Scott Sauyet Jun 24 '20 at 16:24
  • 2
    @ScottSauyet OP didn't ask for a better solution. OP asked why the "copy" of his array get sorted too, hence it's a duplicate – ibrahim mahrir Jun 24 '20 at 16:25
  • This totally makes sense. Thank you for the feedback – tryingCode Jun 24 '20 at 16:48

2 Answers2

1

As the comments pointed out, you can look to another answer to display ways of making shallow or deep copies of an array.

But you noted that your sort is not the best way to find the minimum length. This version is simpler, to my mind. We use map to get the string lengths and then Math.min to take the smallest one. Then we map the array as you did in your first answer. The code ends up much simpler:

const cutIt = (arr) => {
  const shortest = Math .min (...arr .map (s => s .length))
  return arr .map (s => s .slice (0, shortest))
}

console .log (
  cutIt (['disappointed', 'joyous', 'happy', 'sad', 'upset'])
)
Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
  • 3
    This question and your answer are [being discussed on Meta](https://meta.stackoverflow.com/questions/398720/is-a-question-still-a-duplicate-if-there-are-better-ways-to-solve-the-underlying) – Machavity Jun 24 '20 at 17:00
  • @Machavity: Thanks for the heads-up. – Scott Sauyet Jun 24 '20 at 18:02
0

try this code. it makes a copy of input array

let sortedArr = [...arr].sort((a, b) => a.length - b.length);
Ehsan Nazeri
  • 771
  • 1
  • 6
  • 10