Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify an array without mutation

I am trying to solve a problem which states to remove(delete) the smallest number in an array without the order of the elements to the left of the smallest element getting changed . My code is -:

function removeSmallest(numbers){
    var x =  Math.min.apply(null,numbers);
    var y = numbers.indexOf(x);
    numbers.splice(y,1);
    return numbers;
}

It is strictly given in the instructions not to mutate the original array/list. But I am getting an error stating that you have mutated original array/list . How do I remove the error?

like image 851
red assault Avatar asked Jan 01 '23 23:01

red assault


2 Answers

Listen Do not use SPLICE here. There is great known mistake rookies and expert do when they use splice and slice interchangeably without keeping the effects in mind.

SPLICE will mutate original array while SLICE will shallow copy the original array and return the portion of array upon given conditions.

Here Slice will create a new array

const slicedArray = numbers.slice()
const result = slicedArray.splice(y,1);

and You get the result without mutating original array.

like image 84
Sakhi Mansoor Avatar answered Jan 04 '23 11:01

Sakhi Mansoor


first create a copy of the array using slice, then splice that

function removeSmallest(numbers){
    var x =  Math.min.apply(null,numbers);
    var y = numbers.indexOf(x);
    return numbers.slice().splice(y,1);
}
like image 42
basbase Avatar answered Jan 04 '23 11:01

basbase