Move object from one array to another

Miguel Frias picture Miguel Frias · Aug 28, 2017 · Viewed 13.2k times · Source

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.

public $onInit(): void {
  this.getTicket();
}

public ticket: any; // Object with the array
public comments: any = []; // New array to move the elements
public getTicket(): void {
    this.ticketService
        .getTicketComplete(this.$stateParams.ticketID)
        .then((response: any) => {
            this.ticket = response;
            this.stringToDate(this.ticket);
            this.ticket.messages.forEach((elem, index) => {
                if (elem.type === "comment") {
                    this.ticket.messages.splice(index, 1);
                    this.comments.push(elem);
                }
            });
            console.log(this.ticket);
    });
}

the problem that i have is the next one: the array has to types of objects, messages and comments, if the array has 2 messages and 3 comments it should push to the new array 3 comments and leave 2 messages, but is moving only 2 comments.

Any idea. Thanks for your help.

Answer

Arg0n picture Arg0n · Aug 28, 2017

This is the way You do it:

var array1 = [1, 2, 3, 4, 5];
var array2 = [];

array1.forEach(function(elem, index) {
  array1.splice(index, 1);
  array2.push(elem);
});

console.log(array1); //[2, 4]
console.log(array2); //[1, 3, 5]

This is an example of how it can be done:

var array1 = [1, 2, 3, 4, 5];
var array2 = [];

for(var i = 0; i < array1.length; i++) {
  array2.push(array1[i]);
  array1.splice(i, 1);
  i--; //decrement i IF we remove an item
}

console.log(array1); //[]
console.log(array2); //[1, 2, 3, 4, 5]

Specific use-case for you:

let messages = this.ticket.messages;
for(let i = 0; i < messages.length; i++) {
  let message = messages[i];
  if (message.type === "comment") {
    this.comments.push(message);
    messages.splice(i, 1);
    i--;
  }
}