3
\$\begingroup\$

I have an array of objects:

const dataset = [
  {name: 'Marie', year: 12, country: 'Canada'},
  {name: 'Jeff', year: 18, country: 'France'},
  {name: 'Joss', year: 10, country: 'Spain'},
  {name: 'Carrie', year: 45, country: 'Belgium'},
  {name: 'Linda', year: 32, country: 'France'},
]

I want two array: one with names and one with countries:

const names = ['Marie', 'Jeff', 'Joss', 'Carrie', 'Linda']
const countries = ['Canada', 'France', 'Spain', 'Belgium', 'France']

So, I usually do:

const names = dataset.map(e => e.name)
const countries = dataset.map(e => e.country)

Is there a simplest way possibly using a single loop?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

I'm not sure this is any simpler but it does use only a single loop:

 const dataset={ ... }
 const names=[], countries=[]
 for (var d of dataset) { 
     names.push(d.name); 
     countries.push(d.country);
 }

Surprisingly, according to jsben.ch, this approach is about 6 times faster than running map twice.

\$\endgroup\$
5
  • 3
    \$\begingroup\$ You can get about another 20% performance increase if you pre-allocate the array length and use destructuring to reduce the property lookup time. const names = new Array(dataset.length), countries = new Array(dataset.length); var idx = 0; for(const {name, country} of dataset) { names[idx] = name; countries[idx++] = country } \$\endgroup\$
    – Blindman67
    Commented Feb 27, 2019 at 9:58
  • \$\begingroup\$ @Blindman67 that is good info. Do you know why map is so much slower? \$\endgroup\$ Commented Feb 27, 2019 at 10:09
  • 1
    \$\begingroup\$ Iterating the dataset twice. The overhead of a new context each time the callback is called, though you only use the first argument, the callback is passed three, and there is the preliminary, vetting and setup when map is called. You will find that map does better (improves not better than) in comparison when the array length is longer. \$\endgroup\$
    – Blindman67
    Commented Feb 27, 2019 at 10:20
  • \$\begingroup\$ That test tells me that map is almost twice as fast. With Blindman67's improvements they are about the same. \$\endgroup\$
    – Kruga
    Commented Feb 28, 2019 at 10:11
  • \$\begingroup\$ I was testing in Firefox. In Chrome I see what you see and map is faster there. \$\endgroup\$ Commented Feb 28, 2019 at 10:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.