I have the following array
[{price: 65, date: 11-02-2020}, {price: 69, date: 11-02-2020}, {price: 34, date: 11-02-2020}]
How could I make an array of prices and an array dates. Without having to use a for or foreach loop?
I have the following array
[{price: 65, date: 11-02-2020}, {price: 69, date: 11-02-2020}, {price: 34, date: 11-02-2020}]
How could I make an array of prices and an array dates. Without having to use a for or foreach loop?
You can use map() to build an array with specific members :
const datas = [{price: 65, date: '11-02-2020'}, {price: 69, date: '11-02-2020'}, {price: 34, date: '11-02-2020'}];
const prices = datas.map(elem => elem.price);
const dates = datas.map(elem => elem.date);
console.log(prices);
console.log(dates);
However, this does 2 loops under the hood. Using a good old loop can divide the time complexity by 2 :
const datas = [{price: 65, date: '11-02-2020'}, {price: 69, date: '11-02-2020'}, {price: 34, date: '11-02-2020'}];
const prices = [];
const dates = [];
for (let i = 0, len = datas.length; i < len; i++)
{
prices.push(datas[i].price);
dates.push(datas[i].date);
}
console.log(prices);
console.log(dates);
pushes. So, at best, you've eliminated 1/2 of the work done by (at best) half of the code.