Remove object from the current array in foreach?

Asked

Viewed 911 times

-1

I need to remove from the array the current object being processed:

arrai = [{parent:1,dialog_node:2}, {parent:1,dialog_node:3}, {parent:1,dialog_node:4}, {parent:9,dialog_node:1}, {parent:9,dialog_node:6}];
tree = {parent:1,dialog_node:2};
arrai.forEach(function(value){
              if(tree.parent == value.parent){
                  node.parent = value.parent;
                  node.children.push(value.dialog_node);
                  _.reject(arrai, function(el) { 
                         return el.dialog_node === tree.dialog_node; });
                    }
              });

I would like to end the elements that fit into the if are out of the array.

  • if you have the example of this array?

  • 1

    remove an item from the array in which the forEach is running is not a good idea, better add a reference to everything you want to remove in another array, and after the forEach rule out everything

  • Adjusted @Virgilionovic

1 answer

2

To remove an item from the Array during the interaction, the interesting thing is to perform the interaction starting at the end.:

var lista = [
  { id: 1, text: 'texto 01' },
  { id: 2, text: 'texto 02' },
  { id: 3, text: 'texto 03' },
  { id: 4, text: 'texto 04' },
  { id: 5, text: 'texto 05' },
];

lista.reverse()
for (var i = lista.length -1; i >=0; i--) {
  var item = lista[i];
  lista.splice(i, 1);  
  console.log(item)
}

console.log(lista)

another possibility is the use of filter, since filter will not modify the original list.

var lista = [
  { id: 1, text: 'texto 01' },
  { id: 2, text: 'texto 02' },
  { id: 3, text: 'texto 03' },
  { id: 4, text: 'texto 04' },
  { id: 5, text: 'texto 05' },
];

lista = lista.filter(function (item, i) {
  console.log(item);
  return false;
})

console.log(lista)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.