javascript - How can I change the position of a particular item in an array? -
i'm trying change item's index position in array, cannot figure out way.
{ "items": [ 1, 3, 2 ] }
you can use splice move element in array:
var arr = [ 1, 3, 2 ]; var oldindex = 2, newindex = 1; arr.splice(newindex, 0, arr.splice(oldindex, 1)[0]); this makes [1, 2, 3]
the internal splice removes , returns element, while external 1 inserts back.
just fun defined generic function able move slice, not element, , doing computation of index:
object.defineproperty(array.prototype, "move", { value:function(oldindex, newindex, nbelements){ this.splice.apply( this, [newindex-nbelements*(newindex>oldindex), 0].concat(this.splice(oldindex, nbelements)) ); } }); var arr = [0, 1, 2, 7, 8, 3, 4, 5, 6, 9]; arr.move(5, 3, 4); console.log('1:', arr) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] var arr = [0, 1, 2, 7, 8, 3, 4, 5, 6, 9]; arr.move(3, 9, 2); console.log('2:', arr); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] var arr = [0, 1, 2, 4, 5, 3, 6, 7]; arr.move(5, 3, 1); console.log('3:', arr); // [0, 1, 2, 3, 4, 5, 6, 7] var arr = [0, 3, 1, 2, 4, 5, 6, 7]; arr.move(1, 4, 1); console.log('3:', arr); // [0, 1, 2, 3, 4, 5, 6, 7]
Comments
Post a Comment