Javascript array referencing an array position (not an element)

  • A+


Many asked why not using [arr[0], arr[1]]. The problem is I have to pass this array to a method, which I don't have access Angular Material Table. And I don't want to call the method over and over again.

I already processed the arr array and I don't want to process pointer array to reflect the new data, which I already know where it is.

The Nina Scholz answer seems to solve the problem.

Is there a way to use "pointers" like C in Javascript?

What I want to do is:

I have an array with objects

const arr = [     {prop: 3},     {prop: 4}, ]; 

And I want to have an array to point to the positions of this array

const pointer = [arr[0], arr[1]]; // I want pointer to point to be an array containing the first and second elements of arr 

This will get a reference to the {prop: 3} and {prop: 4} objects, which is not what I want, because, if I do:

arr.splice(0, 0, {prop: 1}); // arr => [{prop:1},{prop:3},{prop:4}] console.log(pointer); // [{prop: 3},{prop: 4}] 

As you can see, pointer holds a reference to the objects {prop:3} and {prop:4}.

How can I achieve pointer to hold reference to the position 0 of the array, instead of the object stored in it? So, on this example, pointer => [{prop:1},{prop:3}]?

I can't call pointer = [arr[0], arr[1]] all the time because arr will change constantly and asynchronously.

Is there a "reactive" way to handle arrays?


If your pointers are always to the same array, you can simply store the indexes.

const pointer = [0, 1]; 

Then you would use:

console.log( => arr[ptr])); 

If your pointers can point to different arrays, you can make the elements of pointer be objects that contain references to the array along with their indexes.

const pointer = [{a: arr, i: 0}, {a: arr1, i: 1}]; console.log({a, i}) => a[i])); 

Interesting aside: several decades ago I used a C implementation for Symbolics Lisp Machines. This is basically how it represented C pointers.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: