Move object from one array to another

后端 未结 3 1072
暗喜
暗喜 2021-01-13 23:07

i have one object that one of the properties is an array of objects, the idea is to move objects from that array to no new one if one condition is true.

publ         


        
3条回答
  •  不知归路
    2021-01-13 23:51

    Here we go the async way baby:

    var array1 = [1, 2, 3, 4, 5];
    var array2 = [];
    
    async function fillArray() {
      array1.forEach(function(elem, index) {
        console.log("elem: ", elem)
        array2.push(elem); 
      })
    }
    
    async function emptyArray(){
      fillArray().then(() =>{
        array1.length = 0; 
     })
    }
    
    emptyArray().then(() => { 
      console.log("array1: ", array1); //[]
      console.log("array2: ", array2); //[1, 2, 3, 4, 5]
    })

    An another great move, conditional way, cheer:

    var array1 = [1, 2, 3, 4, 5];
    var array1Length= array1.length;
    var array2 = [];
     
      array1.forEach((elem, index) => {
        array2.push(elem); 
        if(array2.length === array1Length) array1.length=0
      })
      
      console.log("array1: ", array1); //[]
      console.log("array2: ", array2); //[1, 2, 3, 4, 5] 

提交回复
热议问题