0

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?

3
  • 1
    What is wrong with using a loop? Commented Feb 11, 2020 at 13:13
  • I meant for / foreach loop. Could this be done with array.map() ? Or some function that doesn't obfuscate the code? Commented Feb 11, 2020 at 13:17
  • In what way does a for loop obfuscate the code? Commented Feb 11, 2020 at 13:34

1 Answer 1

1

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);

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

5 Comments

I'd be surprised if the good old loop halved the execution time; it wouldn't surprise me if it actually ran slower.
@ScottHunter could be, indeed, we might need some benchmarks
So "can divide the time complexity by 2" was a bit premature?
Well, that's a supposition, hence the "can" instead of "will"
Except it can't since you still do the same number of pushes. So, at best, you've eliminated 1/2 of the work done by (at best) half of the code.

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.