AJavaStudent
AJavaStudent

Reputation: 83

Why does array.map not return a new array?

I want to create a copy of an array using the map function, but instead, I get the same reference. I don't understand why. I would like to have an alternative way to create a copy of an array.

I used the map function to create a copy of the original array and then used the filter function on the copy to mutate a single element. I would expect that the original array would not be mutated, but it actually is.

Can someone give me background info on why this is happening and also the right way to really copy an array, creating a reference to a different object?

const arr = [{name: 'hello'}, {name: 'world'}] 
const arr2 = arr.map(i => i)
const [partial] = arr2.filter(i => i.name === 'hello')
partial.name = 'HELLO'
arr2[0].name === 'HELLO' // true
arr[0].name === 'HELLO' // true

Upvotes: 4

Views: 6421

Answers (1)

jo_va
jo_va

Reputation: 13964

Object and Arrays are reference types in JavaScript, which means, when you copy them, you are copying their reference, which still points to the original object.

So when you map with:

const arr2 = arr.map(i => i);

you are copying the items from arr to arr2 one by one. And since these items are objects, only their references is copied. You do have two distinct arrays, but they contain references to the same objects.

You could instead do a shallow copy of the inner objects using the spread operator when mapping:

const arr = [{name: 'hello'}, {name: 'world'}] 

const arr2 = arr.map(o => ({ ...o })) // spread operator + implicit return notation

arr[0].name = 'bye';
console.log(arr[0].name, arr2[0].name);

As mentionned by @3limin4t0r in the comments, you can also use Object.assign({}, o) instead of { ...o } to do a shallow copy, since the spread operator for properties is currently in ECMAScript proposal stage 4:

const arr = [{name: 'hello'}, {name: 'world'}] 

const arr2 = arr.map(o => Object.assign({}, o))

arr[0].name = 'bye';
console.log(arr[0].name, arr2[0].name);

Upvotes: 3

Related Questions