javascript return reference to array item javascript return reference to array item arrays arrays

javascript return reference to array item


I tried to use Array.filter() function, but it returns a new array instead of a reference to the original array. which I can not use to mutate the original array.

It returns a new array, but the array's entries are still references to the same objects. So filter is just fine for this.

var filteredUsers = users.filter(function(entry) { return entry.id === 2; });var item = filteredUsers[0];item.name = "user2 name updated";console.log(users[1].name) // "user2 name updated"

The array contains references to the objects, not copies of them. When we do item = users[1], or use filter to get a new array containing a subset of the objects, we get a copy of the object reference, and so the variable now refers to the same object, like this:

+-------+| users |+-------+          |   0   |--------->+---------------+|       |          | id:   1       ||       |          | name: "name1" |          +---------------+|       |          +---------------+          | filteredUsers ||       |                                     +---------------+|   1   |--------->+---------------+<---------|       0       ||       |          | id:   2       |          +---------------+|       |          | name: "name2" ||       |          |               |          +------+|       |          +---------------+<---------| item |+-------+                                     +------+

Changing the object changes the object, and those changes are visible regardless of which reference to the object you use to look at its properties.

Now if you had an array of primitives:

var a = [1, 2, 3, 4, 5];

...then of course, you can't use the approach above because they aren't objects. In that case, you'd use indexOf to find the index:

var index = a.indexOf(3); // Find the first entry === 3

...and then modify the entry

a[index] = 42;

This also applies to strings (provided they're nice normal string primitives, not things you created via new String(), which there's virtually never a reason to do).


To do it similarly to the accepted answer, but a bit more succinctly, let us use Array.find, like so:

var item = users.find(u => u.id === 2)item.name = "user2 name updated"console.log(users[1].name) // "user2 name updated"

Explanations are very similar to what has been provided in the accepted answer.


You can use findIndex(), for example:

var users = [{id:1, name:'name1'},{id:2, name:'name2'}]var idx = users.findIndex(item => item.id === 2);var u = users[idx]; // the reference of user2u.name = "name changed."; // same as `users[idx].name = "name changed.";`