-1

I am currently learning Angular and have found example of the code that is a bit mysterious for me.

I have a function that return Observable<Product[]> array of objects:

  connect(): Observable<Product[]> {

    const dataMutations = [
      this.productsSubject,
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map((products) => {
      this.paginator.length = products.length;
      return this.getPagedData(this.getSortedData([...products]));
    }));
  }

In this code block, there is the function getSortedData that takes [...products] what is purpose of the ... before the array of products?

Code sample of the getSortedData:

private getSortedData(data: Product[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'title': return compare(a.title, b.title, isAsc);
        default: return 0;
      }
    });
  }
veben
  • 8,680
  • 11
  • 48
  • 57
Oleg Gordiichuk
  • 13,891
  • 5
  • 52
  • 91

3 Answers3

3

It's Spread syntax

More info: https://code4developers.com/spread-syntax-in-javascript/

phucnh
  • 823
  • 5
  • 10
2

From MDN web docs Spread Syntax:

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

From MDN web docs Rest parameters:

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

David Walschots
  • 10,733
  • 5
  • 33
  • 53
Michal Cumpl
  • 847
  • 6
  • 12
2

It represents the es6 spread operator. In your case, it allows you to pass a shallow copy of your products array.

veben
  • 8,680
  • 11
  • 48
  • 57