Search code examples
javascriptarrayspass-by-referenceswap

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


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

Solution

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