I've written a function which is supposed to update the objects within an array with a location property. It's passing all tests except for ensuring the original input isn't mutated.
function updateRemoteStudents (arr) { const alteredArr = [...arr] alteredArr.map(person => { if (person.hasOwnProperty('location') === false) { person.location = 'remote'; } }) return alteredArr; } test('original array has not been mutated', () => { const input = [ { name: 'Hypatia', age: 31, location: 'leeds' }, { name: 'Ramanujan', age: 22 }, { name: 'Tao', age: 47, location: 'manchester' } ] updateRemoteStudents(input); expect(input).toEqual([ { name: 'Hypatia', age: 31, location: 'leeds' }, { name: 'Ramanujan', age: 22 }, { name: 'Tao', age: 47, location: 'manchester' } ]) }) My understanding is that if I pass in the array with a spread operator, this should create a shallow copy of the array and thus shouldn't mutate the original, but it's still failing the test, with the changes also being made to the original array. I have also tried using slice and Array.from to no avail. This leads me to suspect that there's something I haven't quite grasped about mutation.
map()would have dealt with anyway, the mutation is happening on the objects themselves which you never clone and so are mutated in the input and references returned to the new array. Ff you don't want to mutate the objects you need to return a copy from themap(). see transform an array of objects with map( )return arr.map((person) => ({...person, location: person.location ?? 'remote',}));