Move an array element from one array position to another

后端 未结 30 2532
渐次进展
渐次进展 2020-11-22 08:36

I\'m having a hard time figuring out how to move an array element. For example, given the following:

var arr = [ \'a\', \'b\', \'c\', \'d\', \'e\'];
<         


        
30条回答
  •  死守一世寂寞
    2020-11-22 08:53

    var ELEMS = ['a', 'b', 'c', 'd', 'e'];
    /*
        Source item will remove and it will be placed just after destination
    */
    function moveItemTo(sourceItem, destItem, elements) {
        var sourceIndex = elements.indexOf(sourceItem);
        var destIndex = elements.indexOf(destItem);
        if (sourceIndex >= -1 && destIndex > -1) {
            elements.splice(destIndex, 0, elements.splice(sourceIndex, 1)[0]);
        }
        return elements;
    }
    console.log('Init: ', ELEMS);
    var result = moveItemTo('a', 'c', ELEMS);
    console.log('BeforeAfter: ', result);

提交回复
热议问题