-->

[removed] How can I swap elements of an array of o

2020-04-17 03:53发布

问题:

I have an array of objects a=[ {v:0}, {v:1}, {v:2}, {v:3} ] ;

I do not have the index into the array, but I do have references to the 2 values I want to swap

s1=a[2] ; s2 = a[3] ;

How do I use these references to swap the elements of the actual array?

[s1,s2] = [s2,s1] ; // only swaps s1 and s2, NOT elements of the array

// a is unchanged

回答1:

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))



回答2:

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.



回答3:

Here is a one liner, just in case:

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


回答4:

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;
  });
}