[removed] move objects from one array to another: Best approach?

后端 未结 7 705
臣服心动
臣服心动 2021-01-04 01:38

I have two arrays, called \'objects\' and \'appliedObjects\'. I\'m trying to come up with an elegant way in Javascript and/or Angular to move objects from one array to anot

7条回答
  •  醉酒成梦
    2021-01-04 02:07

    When a construct does too much automatically (like forEach, or even a for-loop, in this case), use a more primitive construct that allows you to say what should happen clearly, without need to work around the construct. Using a while loop, you can express what needs to happen without resorting to backing up or otherwise applying workarounds:

    function moveSelected(src, dest)  {
        var i = 0;
        while ( i < src.length ) {
            var item = src[i];
            if (item.selected) {
                src.splice(i,1);
                dest.push(item);
            }
            else i++;
        }
    }
    

提交回复
热议问题