1

I have an array, like

Array[{id:0,name:"a"},{id:1,name:"b"}...]

I have an other array, let's call it Array2, in Array2 I want those items from Arraywhere the id = given number.
I'm trying this with a function like:

saveActualComment() {
    var i = 0;
    for (i = 0; i < this.postComments.length; i++) {
      if (this.postComments[i].postid = this.post.id) {
        this.actualComments.push(this.postComments[i]);
      }
    }
  }

Where postCommets is the Array, and actualComments is the Array2.
Problem is, that this function always gives me back the whole array, not only those items where the Array.id is the given number (post.id)

7
  • Have you tried to use compare operator instead of assigning value? Commented Jul 12, 2018 at 19:32
  • @yurzui not yet, but will give it a try Commented Jul 12, 2018 at 19:33
  • Yes, as mentioned you are assigning to this.postComments[i].postid instead of comparing its value. Use a double or triple equals instead, eg: if (this.postComments[i].postid === this.post.id) { ... } Commented Jul 12, 2018 at 19:37
  • @Skickpause not sure if typo but it should be == in the if clause. Commented Jul 12, 2018 at 19:37
  • @Ploppy It's a shame, but it's a typo Commented Jul 12, 2018 at 19:41

1 Answer 1

3
if (this.postComments[i].postid = this.post.id) {
        this.actualComments.push(this.postComments[i]);
      }

in above code use == instead of =

this.postComments[i].postid == this.post.id

or you can do this

this.actualComments = this.postComments.filter((item) => item.postId === this.post.id);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you :) So it was just a typo.., and thank you for the other solution, I haven't known that I can do this Array.filter
yeah you can do more then just filter.. look at this tutorial medium.com/poka-techblog/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.