Javascript array element indexOf is -1 after swap of element positions with splice -
our array has 2 elements of type object this:
array = [{member1: "value1"},{member2: "value2"}];
when index of second object this:
var index = array.indexof(obj);
i 1 result, fine. when swap 2 elements shift object right left , other 0 index object left right:
var new_index = index - 1; array.splice(index, 0, array.splice(new_index, 1)[0]);
and try index of same object (which know present in array , index 0 now) -1 (not found) result. whats problem here?
as want swap, rather splicing may better use temporary variable.
var array = [{member1: "value1"},{member2: "value2"}], obj = array[1]; function swap(arr, i, j) { var t = arr[i]; arr[i] = arr[j]; arr[j] = t; return arr; } console.log('before swap', array.indexof(obj)); // 1 swap(array, 0, 1); console.log('after swap', array.indexof(obj)); // 0
edit tried code though , expected result of 0
, maybe you've done reference obj
pointing @ between two
Comments
Post a Comment