user8951490
user8951490

Reputation: 843

TypeScript/Angular: TypeError when attemting to concat two arrays together

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.

Upvotes: 0

Views: 199

Answers (3)

Pardeep Jain
Pardeep Jain

Reputation: 86740

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

Upvotes: 2

Adrii
Adrii

Reputation: 1740

You can use spread operator, just like this ->

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

Upvotes: 1

Carsten
Carsten

Reputation: 4208

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

Upvotes: 0

Related Questions