1

Problem: I want to bind the values in an array in a way that when I change one value the other one will change aswell and vice versa.

var array = [1,2,3,1];
array[0] = array[3];
array[0] = 7;
console.log(array[3]) //this will give 1 and I need 7 here.

I figured out a way to do this with objects, but it is not as clean as I would like it to be. My friend told me there was no way this could be done but I doubt it.

4
  • 4
    And the logic behind getting 7? Commented Jun 11, 2018 at 16:10
  • you need to write your own logic for this Commented Jun 11, 2018 at 16:11
  • I would assume they're looking for references (array[3] refs array[0]) which you won't find in JS without objects. Commented Jun 11, 2018 at 16:13
  • Only objects in javascript can be assigned as reference and you're passing value of array[3] which is of type Number in your case, and not reference. Commented Jun 11, 2018 at 16:36

1 Answer 1

2

Just use objects and reference them:

var array = [{v: 1}, {v: 2}, {v: 3}, {v: 1}];
array[0] = array[3];
array[0].v = 7;
console.log(array[3].v);

To get slightly more readable code, you might wanna implement a custom map:

class LinkMap extends Map {
  get(k) {
     return (super.get(k) || {}).value;
  }
  set(k, value) {
     if(super.has(k)) {
       super.get(k).value = value;
     } else {
      super.set(k, { value });
     }
  }
  link(key, to) {
    return super.set(to, super.get(key));
  }
}

So one can do:

const list = new LinkMap();
 list.set(0, 1).set(1, 2).set(2, 3).link(0, 4);
 list.set(4, 7);
 console.log(list.get(0));
Sign up to request clarification or add additional context in comments.

1 Comment

Just to complement: What you are trying to do is not possible with numbers or strings which are accessed by value. So by using an object, you access the reference of the object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.