Solved various puzzles with JavaScript'a . And I stumbled on this: The goal is to remove the minimum value from the array, despite the fact that the location of the elements should not change, I sort of coped with the task, but the site does not skip, one test fails. Writes that it is necessary to check for a mutated array.

enter image description here

 function removeSmallest(numbers) { var min, minindex; min = numbers[0]; minindex = 0; for(var i = 0; i < numbers.length; i++) { if(min > numbers[i]) { min = numbers[i]; minindex = i; } } numbers.splice(minindex, 1) return numbers; } 

What am I doing wrong and what kind of check should I do? Problem with codewars

  • It is written in red on black - you changed the array that numbers . What to do - do not change the numbers - andreymal

1 answer 1

In the argument, you get a link to the array that was passed from the test, not a copy of the array. In the code you mutate (change) it through the splice function. The solution is to make a copy of the array: numbers = [...numbersInput] . Or you can use a solution that does not mutate the array.

 function removeSmallest (numbersInput) { var numbers, min, minindex; numbers = [...numbersInput]; // копия массива min = numbers[0]; minindex = 0; for (var i = 0; i < numbers.length; i++) { if (min > numbers[i]) { min = numbers[i]; minindex = i; } } numbers.splice(minindex, 1) return numbers; } console.log(removeSmallest([2, 50, 51, 60])) 

Here is my solution and how to do it according to your idea but through findIndex :

 console.log(removeSmallest([2, 50, 51, 60])) console.log(removeSmallest2([2, 50, 51, 60])) function removeSmallest (numbers) { const min = Math.min(...numbers) // ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·Π²Ρ‹Π²Π°Π΅Ρ‚ массив Π² Π°Ρ€Π³ΡƒΠΌΠ΅Π½Ρ‚Ρ‹ return numbers.filter(i => i !== min) // это Π½Π΅ ΠΌΡƒΡ‚ΠΈΡ€ΡƒΠ΅Ρ‚ исходный массив, Π° Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ ΠΌΠΎΠ΄ΠΈΡ„ΠΈΡ†ΠΈΡ€ΠΎΠ²Π°Π½Ρ‹ΠΉ } function removeSmallest2 (numbersInput) { let numbers = [...numbersInput] // копия массива const min = Math.min(...numbers) const minIndex = numbers.findIndex(i => i === min) numbers.splice(minIndex, 1) return numbers; }