0

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.

4
  • It is a shallow copy, which 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 the map(). see transform an array of objects with map( ) Commented Apr 24, 2023 at 8:55
  • 1
    Does this answer your question? transform an array of objects with map( ) Commented Apr 24, 2023 at 8:59
  • In short, you need to spread each object, not the containing array return arr.map((person) => ({...person, location: person.location ?? 'remote',})); Commented Apr 24, 2023 at 9:08
  • also Updating an array of objects without mutation Commented Apr 24, 2023 at 9:57

1 Answer 1

0

The problem is not that the array is mutated, but an anonymous person object which input references.

To achieve the effect of creating 'before' and 'after' arrays, you can create a new object from the existing one.

function updateRemoteStudents(arr) { const alteredArr = [...arr]; alteredArr.map((person,index) => { if (person.hasOwnProperty('location') === false) alteredArr[index]={...person,location:'remote'}; }); return alteredArr; } const input = [ { name: 'Hypatia', age: 31, location: 'leeds' }, { name: 'Ramanujan', age: 22 }, { name: 'Tao', age: 47, location: 'manchester' } ]; console.log(updateRemoteStudents(input)); console.log(input);

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.