0

I am trying to concat two arrays of the same type together. The two arrays are actually nested in a "parent" array. So, the goal is to just flatten it out.

This is the code that I am using:

ngOnInit() {
    this.Logs.getAllLogs()
      .subscribe(logs => {
        this.Logs = Object.values(logs);
        console.log('First: ', this.Logs[0]);
        console.log('Second: ', this.Logs[1]);
        this.mergedLogs = this.Logs[0].concat(this.Logs[1]);
        console.log('Together: ', this.mergedLogs);
      });   }

But I am getting this error:

ERROR TypeError: _this.Logs[0].concat is not a function

EDIT: Some users suggested to use a spread operator, so the code was then changed to:

ngOnInit() {
    this.Logs.getAllLogs()
      .subscribe(logs => {
        this.Logs = Object.values(logs);
        console.log('First: ', this.Logs[0]);
        console.log('Second: ', this.Logs[1]);
        this.mergedLogs = [...this.Logs[0], ...this.Logs[1]];
        console.log('Together: ', this.mergedLogs);
      });
  }

But somehow I still get the same exact error. When I comment out the line where the arrays are merged, the page refreshes fine, so it is not a caching issue.

2
  • Are you 100% sure that this.Logs is an array of arrays? I find it a bit strange, can you post a console.log of it? Commented May 17, 2018 at 8:04
  • 1
    You nailed it, bugs. I wrongly assumed they were an array because that is what Object.values() returns, but I had not run Object.values() on the sub-arrays--so they were still objects and the object rest spread operator did the trick.... Sorry to everyone who took the time, your solutions would have been correct had they been arrays. Commented May 17, 2018 at 8:17

3 Answers 3

2

Instead of using concat() to concatenate arrays, you could try using spread operator ... if you have an array of the same type.

Use below code like this -

  this.mergedLogs = [...this.Logs[0],...this.Logs[1]);

For more information and example you could look here

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, the error is persisting with the same problem. I thought it worked previously but I made a mistake.
1

You can use spread operator, just like this ->

this.mergedLogs = [...this.Logs[0], ...this.Logs[1]];

Comments

0

The first very obvious mistake you made is that you are working with this.Logs instead of logs inside your subscribe callback.

1 Comment

OP have assigned logs to this.Logs so what's wrong in this?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.