Remove object from current array in foreach?

-1

I need to remove from 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 the elements that fall within if to be outside the array at the end.

    
asked by anonymous 26.03.2018 / 16:18

1 answer

1

To remove an item from the Array during the interaction, the interesting thing is to do 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 to use filter , since the 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)
    
26.03.2018 / 16:30