0

Let's say that I have an array of objects like this:

var messages = [
    {id: 1, replyTo: null}
    {id: 5, replyTo: null}
    {id: 7, replyTo: null}
    {id: 9, replyTo: 7}
    {id: 10, replyTo: null}
    {id: 12, replyTo: 1}
    {id: 16, replyTo: 1}
    {id: 20, replyTo: 1}
    {id: 24, replyTo: 1}
    {id: 28, replyTo: 1}
    {id: 32, replyTo: 1}
    {id: 36, replyTo: 1}
    {id: 40, replyTo: 1}
];

And that I want to remove all objects from that array that has a property id of 1, but also a replyTo of 1.

I tried something like this:

for (var i = 0; i < messages.length; i++) {
    if (messages[i].id === 1 || messages[i].replyTo === 1) {
        messages.splice(i, 1);
    }
}

And this did not work.

How can I solve this problem?

Alex
  • 5,671
  • 9
  • 41
  • 81
  • 1
    if you are fine with generating a new array, use [`.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). – Felix Kling May 11 '16 at 03:19
  • create new array of certain values is better than modify old array – daremachine May 11 '16 at 03:21
  • 1
    The reason why your code doesn't work is because you are moving your index forward through the array. If you simply move your index in reverse order `i--`, your attempt will work. – Matt Way May 11 '16 at 03:24
  • Oh I see now. Thanks! – Alex May 11 '16 at 03:48

2 Answers2

2

Use filter like this

var filteredMessages = messages.filter(function(message) {
    return message.id !== 1 || message.replyTo !== 1;
});
winhowes
  • 7,845
  • 5
  • 28
  • 39
0

You can use the filter method. In first filtering removing removing all elements with property id 1 ,in second turn removing elements with replyTo is 1

var messages = [
    {id: 1, replyTo: null},
    {id: 5, replyTo: null},
    {id: 7, replyTo: null},
    {id: 9, replyTo: 7},
    {id: 10, replyTo: null},
    {id: 12, replyTo: 1},
    {id: 16, replyTo: 1},
    {id: 20, replyTo: 1},
    {id: 24, replyTo: 1},
    {id: 28, replyTo: 1},
    {id: 32, replyTo: 1},
    {id: 36, replyTo: 1},
    {id: 40, replyTo: 1}
];
var newArray = messages.filter(function(item){
  return item.id !==1 
})

var newArray2 = newArray.filter(function(item){
return item.replyTo !==1;
})
console.log(newArray2);

Check this jsFiddle

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
brk
  • 48,835
  • 10
  • 56
  • 78