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