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?

4
  • 1
    if you are fine with generating a new array, use .filter. Commented May 11, 2016 at 3:19
  • create new array of certain values is better than modify old array Commented May 11, 2016 at 3: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. Commented May 11, 2016 at 3:24
  • Oh I see now. Thanks! Commented May 11, 2016 at 3:48

2 Answers 2

2

Use filter like this

var filteredMessages = messages.filter(function(message) {
    return message.id !== 1 || message.replyTo !== 1;
});
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thank you for your suggestion! Much appreciated!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.