0

I have an array like this:

Model:

export class Total {
    Id: number;
    Products: string;
    LastUpdated: Date;
}

I have a list of this with:

myList[] = this.service.getProducts().toPromise();

How do I make a new array with only get Products and LastUpdated from myList?

myProducts[] = ["prod1","prod2","prod3","prod3"];
myDates[] = ["2020-03-01","2020-03-02","2020-03-05","2020-03-06"];

3 Answers 3

2

Use map() function. Try the following

const myProducts = this.myList.map(item => item.Products);
const myDates = this.myList.map(item => item.LastUpdated);
Sign up to request clarification or add additional context in comments.

2 Comments

you can use reduce so you will only iterate through the array once... const [myProcucts, myDates] = this.myList.reduce((total, item) => { total.push([item.Products, item.LastUpdates]) return total }, [] as Array<string[], Date[]>);
@AlexandreDias, ofc you can use reduce, but not that way you did. It gives an unexpected result.
0

I assume that here this.service.getProducts().toPromise(); gives you type Promise<Total[]> (not an array) so you would write myList instead of myList[]. This way, for products and dates its better/saftier to keep them like Promise<string[]> type.

const myProducts = this.myList.then(list => list.map(item => item.Products));
const myDates = this.myList.then(list => list.map(item => item.LastUpdated));

If you are sure that you need string[] type, you can wait for this promise:

this.myList.then(list => {
    this.myProducts = list.map(item => item.Products);
    this.myDates = list.map(item => item.LastUpdated);
});

Comments

0

Using mapyou could achieve the result, but you would need to iterate through the entire array twice, which might be bad on large arrays...

So you can use reduce instead.

const [myProcucts, myDates]: [string[], Date[]] = this.myList.reduce((total: [string[], Date[]], item: Total) => {
        // push product value to the array of Products
        total[0].push(item.Products);

        // push lastUpdated value to the array of lastUpdated
        total[1].push(item.LastUpdated);
        return total
    }, [[],[]]);

Comments

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.