[removed] How can I swap elements of an array of objects (by reference, not index)?

前端 未结 4 1176
挽巷
挽巷 2021-01-22 11:55

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

4条回答
  •  青春惊慌失措
    2021-01-22 12:08

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

提交回复
热议问题