Javascript: How can I swap elements of an array of objects (by reference, not index)?

喜你入骨 提交于 2019-12-02 01:48:54
Mosè Raguzzini

If you have the reference you can safely retrieve the index by Array.indexOf():

a.indexOf(myReference) // returns the index of the reference or -1

Then, with retrieved index, you can proceed as usual.

Like this:

let a = [{ v: 0 }, { v: 1 }, { v: 2 }, { v: 3 }];

const s1 = a[2];
const s2 = a[3];
console.log(a.indexOf(s1))

There is no "pass by reference" in JavaScript. In most cases, the objects act as pointers, not references anyway.

That unfortunately means you will need to find the indexes of the objects and then swap them using those indexes:

// swap here, assumes the objects are really in the array
const s2index = a.indexOf(s2);
a[a.indexOf(s1)] = s2;
a[s2index] = s1;

Depending on your use case, you should check if the objects indeed are in the array.

Here is a one liner, just in case:

a.splice(a.indexOf(s2), 1, a.splice(a.indexOf(s1),1,s2)[0]);

Here's an utility function:

function swap(list, a, b) {
  var copy = list.slice();

  copy[list.indexOf(a)] = b;
  copy[list.indexOf(b)] = a;
  
  return copy;
}

// usage
var a =[ {v:0}, {v:1}, {v:2}, {v:3} ] ;

var result = swap(a, a[1], a[3]);

console.log(result); 
// [ {v:0}, {v:3}, {v:2}, {v:1} ]

Keep in mind, since you are using Objects in your array, you need the exact reference to this value. E.g. this will not work:

var a =[ {v:0}, {v:1}, {v:2}, {v:3} ] ;

var result = swap(a, {v:1}, {v:3});

console.log(result); 
// [ {v:0}, {v:1}, {v:2}, {v:3} ]

Here's an alternative version which checks for all values in an Array:

function swap(list, a, b) {
  return list.map(function(item) {
    if (item === a) {
      return b;
    } else if (item === b) {
      return a;
    }

    return item;
  });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!